golang GRPC 携带上下文信息

使用context.Context

上下文去全局数据 metadata

type MD map[string][]string

//第一种方式
md := metadata.New(map[string]string{"key1": "val1", "key2": "val2"})
 
//第二种方式 key不区分大小写,会被统一转成小写
md := metadata.Pairs(
    "key1", "val1",
    "key1", "val1-2", // "key1" will have map value []string{"val1", "val1-2"}
    "key2", "val2",
)
客户端传值
func (s *server) SomeRPC(ctx context.Context, in *pb.SomeRequest) (*pb.SomeResponse, err) {
    md, ok := metadata.FromIncomingContext(ctx)
    // do something with metadata
}
服务端获取参数
func (s *server) SomeRPC(ctx context.Context, in *pb.SomeRequest) (*pb.SomeResponse, err) {
    md, ok := metadata.FromIncomingContext(ctx)
    // do something with metadata
}
posted @ 2022-05-26 18:49  vx_guanchaoguo0  阅读(137)  评论(0编辑  收藏  举报