Golang GRPC 添加header
创建grpc连接时添加header
使用自建的metadata
添加的headr信息: key: my-header value: "test01"
func main() {
conn, err := grpc.Dial("localhost:12000", grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithPerRPCCredentials(extraMetadata{MyHeader: "test01"}))
}
type extraMetadata struct {
MyHeader string `json:"my-header"`
}
func (c extraMetadata) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"my-header": c.MyHeader,
}, nil
}
func (c extraMetadata) RequireTransportSecurity() bool {
return false
}
执行方法时添加header
添加的headr信息: key: my-header value: "test01"
使用自建的metadata
func main() {
conn, err := grpc.Dial("localhost:12000", grpc.WithTransportCredentials(insecure.NewCredentials()))
c := pb.NewHelloHTTPClient(conn)
req := &pb.HelloHTTPRequest{Name: "test"}
res, err := c.SayHello(context.Background(), req, grpc.PerRPCCredentials(extraMetadata{MyHeader: "test01"}))
}
type extraMetadata struct {
MyHeader string `json:"my-header"`
}
func (c extraMetadata) GetRequestMetadata(ctx context.Context, uri ...string) (map[string]string, error) {
return map[string]string{
"my-header": c.MyHeader,
}, nil
}
func (c extraMetadata) RequireTransportSecurity() bool {
return false
}
使用官方的metadata
func main() {
conn, err := grpc.Dial("localhost:12000", grpc.WithTransportCredentials(insecure.NewCredentials()))
header := metadata.New(map[string]string{
"my-header": "test01",
})
var ctx = metadata.NewOutgoingContext(context.Background(), header)
res, err := c.SayHello(ctx, req)
}
标签:string,header,GRPC,extraMetadata,Golang,grpc,func,my
From: https://www.cnblogs.com/-xuan/p/16876840.html