Golang GRPC 添加header

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)
}

grpcurl 指定header

grpcurl -plaintext -d '{"name": "test"}' -import-path ../ -proto hello_http.proto -rpc-header 'my-header:test01' localhost:12000 hello_http.HelloHTTP/SayHello

posted @ 2022-11-10 14:03  董大轩  阅读(832)  评论(0编辑  收藏  举报