使用 ctx.value 从 context 读取数据
// valuefromincomingcontext returns the metadata value corresponding to the metadata // key from the incoming metadata if it exists. key must be lower-case. // // # experimental // // notice: this api is experimental and may be changed or removed in a // later release. func valuefromincomingcontext(ctx context.context, key string) []string { md, ok := ctx.value(mdincomingkey{}).(md) if !ok { return nil } if v, ok := md[key]; ok { return copyof(v) } for k, v := range md { // we need to manually convert all keys to lower case, because md is a // map, and there's no guarantee that the md attached to the context is // created using our helper functions. if strings.tolower(k) == key { return copyof(v) } } return nil }
使用 ctx.value 往 context 写入数据
// appendtooutgoingcontext returns a new context with the provided kv merged // with any existing metadata in the context. please refer to the documentation // of pairs for a description of kv. func appendtooutgoingcontext(ctx context.context, kv ...string) context.context { if len(kv)%2 == 1 { panic(fmt.sprintf("metadata: appendtooutgoingcontext got an odd number of input pairs for metadata: %d", len(kv))) } md, _ := ctx.value(mdoutgoingkey{}).(rawmd) added := make([][]string, len(md.added)+1) copy(added, md.added) kvcopy := make([]string, 0, len(kv)) for i := 0; i < len(kv); i += 2 { kvcopy = append(kvcopy, strings.tolower(kv[i]), kv[i+1]) } added[len(added)-1] = kvcopy return context.withvalue(ctx, mdoutgoingkey{}, rawmd{md: md.md, added: added}) }
metadata 是 grpc 内置的,用来往 rpc 服务传递 http 头数据,分 in 和 out 两种,对应的 key 都为一个空 struct,分别为:mdincomingkey 和 mdoutgoingkey 。
服务端的 ctx 和 md 直接打印出来,如下样子:
fmt.println(ctx) fmt.println(md) context.background.withvalue(type transport.connectionkey, val <not stringer>).withvalue(type peer.peerkey, val <not stringer>).withdeadline(2024-02-19 10:02:43.212614653 +0800 cst m=+41018.106555206 [1.999790196s]).withvalue(type metadata.mdincomingkey, val <not stringer>).withvalue(type grpc.streamkey, val <not stringer>).withvalue(type baggage.baggagecontextkeytype, val <not stringer>).withvalue(type trace.tracecontextkeytype, val <not stringer>).withvalue(type trace.tracecontextkeytype, val <not stringer>).withcancel map[:authority:[add.rpc] append:[append-value] content-type:[application/grpc] extra:[extra-value] grpc-accept-encoding:[gzip] noncestr:[abc] signature:[0123456789] timestamp:[2021-07-01 00:00:00] traceparent:[00-89415f99d44e6f8f6e14e3fe8f13ad20-bf33b29c4362ca6a-00] user-agent:[grpc-go/1.59.0]] signature: [0123456789]
注意 md 中的值会被加上中括号“[]”。
到此这篇关于grpc-go通过context传递额外数据的文章就介绍到这了,更多相关grpc-go context传递额外数据内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论