首页 > 其他分享 >grpc-go通过context传递额外数据

grpc-go通过context传递额外数据

时间:2024-02-19 10:11:37浏览次数:25  
标签:md grpc WithValue ctx kv context go metadata

  • 使用 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 中的值会被加上中括号“[]”。

标签:md,grpc,WithValue,ctx,kv,context,go,metadata
From: https://www.cnblogs.com/aquester/p/18020497

相关文章

  • Go Gin 框架的模型绑定与验证详解
    GoGin框架的模型绑定与验证详解原创 云原生Go 源自开发者 2024-02-1823:22 广东 听全文源自开发者专注于提供关于Go语言的实用教程、案例分析、最新趋势,以及云原生技术的深度解析和实践经验分享。119篇原创内容公众号在Web开发中,模型绑定和验证......
  • ubuntu Fix The Google GPG Error on Ubuntu
    想装下node.js,结果ubuntu输入aptupdate环境炸了,原因是google的GPGkey更新了报错(base)woodx@Machine:~$sudoaptupdateGet:1file:/var/cudnn-local-repo-ubuntu1804-8.8.1.3InRelease[1,572B]Get:2file:/var/nv-tensorrt-local-repo-ubuntu1804-8.5.1-cuda-11.8InR......
  • go-zero/grpc的rpc服务间传递额外数据
    客户端:md:=metadata.New(map[string]string{"signature":"0123456789","timestamp":"2021-07-0100:00:00"})ctx:=metadata.NewOutgoingContext(ctx,md)addResp,err:=adderClient.Add(ctx,addReq)//rpc调用初始化md也可......
  • google chrome 获取书签的添加日期
    有的时候想找一个书签的添加日期,在浏览器上貌似看不到 设备:win10google书签位置:username是你的用户名C:\Users\username\AppData\Local\Google\Chrome\UserData\Default\Bookmarkspython获取数据importpandasaspdimportjsonimportdatetimewithopen......
  • 跨界协作:借助gRPC实现Python数据分析能力的共享
    gRPC是一个高性能、开源、通用的远程过程调用(RPC)框架,由Google推出。它基于HTTP/2协议标准设计开发,默认采用ProtocolBuffers数据序列化协议,支持多种开发语言。在gRPC中,客户端可以像调用本地对象一样直接调用另一台不同的机器上服务端应用的方法,使得您能够更容易地创建分布式应用......
  • RunnerGo:UI自动化测试神器!
    UI自动化测试已经成为现代软件开发过程中不可或缺的一部分。它能够提供诸多优势,包括提高测试效率、减少人力成本、提升软件质量等。同时,可视化工具为UI自动化测试带来了更多便利和灵活性。RunnerGo近期上线脚本录制器,根据你的测试操作直接生成UI自动化测试脚本,下面是使用方法Step......
  • 饮冰十年-人工智能-ArangoDB-03-AQL
    上一篇:饮冰十年-人工智能-ArangoDB-02-AQLvsSQL本课程的示例数据集基于小说和电视连续剧《三国演义》。它包括两种语言的性格特征、一些人物关系,以及一小部分地点。ToDo:整体完成后补充一、基本CRUD操作1、创建集合我们无法使用AQL创建集合,我们将使用Web界面创建集合......
  • Auth2 django 接入
    原理Auth2的协议说明  https://oauth.net/2/ 相关python包推荐https://oauth.net/code/ 概述场景适用有一个"快浪"的论坛网站,访问者必须要注册用户后才可访问,且允许直接基于 QQ 关联注册,登录访问QQ 不是很随便的怕平台,基于用户授权后,才会同意 快......
  • Go语言指南练习:等价二叉查找树
    题目:不同二叉树的叶节点上可以保存相同的值序列。例如,以下两个二叉树都保存了序列1,1,2,3,5,8,13。在大多数语言中,检查两个二叉树是否保存了相同序列的函数都相当复杂。我们将使用Go的并发和信道来编写一个简单的解法。本例使用了tree包,它定义了类型:typeTreestruct{Lef......
  • Go模仿gin自定义中间件
    packagemainimport( "fmt" "net/http")//中间件函数类型typeMiddlewareFuncfunc(http.HandlerFunc)http.HandlerFunc//自定义中间件1funcLoggerMiddleware(nexthttp.HandlerFunc)http.HandlerFunc{ returnfunc(whttp.ResponseWriter,req*ht......