go-zero开发入门-网关往rpc服务传递数据2

go-zero 的网关服务实际是个 go-zero 的 API 服务,也就是一个 http 服务,或者说 rest 服务。http 转 grpc 使用了开源的 grpcurl 库,当网关需要往 rpc 服务传递额外的数据,比如鉴权数据的时候,通过 http 的 header 进行:

func AuthMiddleware(next http.HandlerFunc, w http.ResponseWriter, r *http.Request) {authResp, err := authClient.Authenticate(r.Context(), &authReq) // 调用鉴权服务r.Header.Set("Grpc-Metadata-myuid", authResp.UserId) // 往 rpc 服务传递额外数据next.ServeHTTP(w, r)
}

rpc 服务端从 metadata 取出数据:

func (l *QueryUserLogic) QueryUser(in *user.UserReq) (*user.UserResp, error) {vals := metadata.ValueFromIncomingContext(l.ctx, "gateway-myuid")uid = vals[0]
}

这里有两个需要注意的地方,在网关侧的名必须以“Grpc-Metadata-”打头,而 rpc 服务端必须以“gateway-”打头,这是 go-zero 的 gateway/internal/headerprocessor.go 写死的规则:

const (metadataHeaderPrefix = "Grpc-Metadata-"metadataPrefix       = "gateway-"
)// ProcessHeaders builds the headers for the gateway from HTTP headers.
func ProcessHeaders(header http.Header) []string {var headers []stringfor k, v := range header {if !strings.HasPrefix(k, metadataHeaderPrefix) { // 判断是否以“Grpc-Metadata-”打头(网关侧传递的)continue // 非以“Grpc-Metadata-”打头的都会被丢弃掉}key := fmt.Sprintf("%s%s", metadataPrefix, strings.TrimPrefix(k, metadataHeaderPrefix)) // 替换为新的前缀“gateway-”(rpc 服务端看到的)for _, vv := range v {headers = append(headers, key+":"+vv)}}return headers
}

调用栈:

(dlv) bt0  0x00000000019da092 in github.com/zeromicro/go-zero/gateway/internal.ProcessHeadersat ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/gateway/internal/headerprocessor.go:151  0x00000000019dc40a in github.com/zeromicro/go-zero/gateway.(*Server).prepareMetadataat ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/gateway/server.go:1752  0x00000000019dbf69 in github.com/zeromicro/go-zero/gateway.(*Server).buildHandler.func1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/gateway/server.go:1323  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:21224  0x00000000008ca162 in net/http.Handler.ServeHTTP-fmat <autogenerated>:15  0x000000000195adc5 in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:21226  0x000000000195adc5 in gateway/middleware.AuthMiddleware // 网关代码at ./Getting-Started-with-Go-zero/gateway_login/gateway/middleware/login_and_auth.go:987  0x000000000195a325 in gateway/middleware.LoginAndAuthMiddleware.func1at ./Getting-Started-with-Go-zero/gateway_login/gateway/middleware/login_and_auth.go:378  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:21229  0x0000000001969169 in github.com/zeromicro/go-zero/rest/handler.GunzipHandler.func1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/gunziphandler.go:26
10  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:2122
11  0x000000000196b3bf in github.com/zeromicro/go-zero/rest/handler.MaxBytesHandler.func2.1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/maxbyteshandler.go:24
12  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:2122
13  0x000000000196ba15 in github.com/zeromicro/go-zero/rest/handler.MetricHandler.func1.1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/metrichandler.go:21
14  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:2122
15  0x000000000196c243 in github.com/zeromicro/go-zero/rest/handler.RecoverHandler.func1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/recoverhandler.go:21
16  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:2122
17  0x000000000196d45c in github.com/zeromicro/go-zero/rest/handler.(*timeoutHandler).ServeHTTP.func1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/timeouthandler.go:82
18  0x0000000000471921 in runtime.goexitat /usr/local/go/src/runtime/asm_amd64.s:1598(dlv) bt0  0x00000000019d636a in google.golang.org/grpc/metadata.NewOutgoingContextat ./go/pkg/mod/google.golang.org/grpc@v1.59.0/metadata/metadata.go:1651  0x00000000019d636a in github.com/fullstorydev/grpcurl.InvokeRPCat ./go/pkg/mod/github.com/fullstorydev/grpcurl@v1.8.9/invoke.go:1362  0x00000000019dc058 in github.com/zeromicro/go-zero/gateway.(*Server).buildHandler.func1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/gateway/server.go:1323  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:21224  0x00000000008ca162 in net/http.Handler.ServeHTTP-fmat <autogenerated>:15  0x000000000195adc5 in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:21226  0x000000000195adc5 in gateway/middleware.AuthMiddleware // 网关代码at ./Getting-Started-with-Go-zero/gateway_login/gateway/middleware/login_and_auth.go:987  0x000000000195a325 in gateway/middleware.LoginAndAuthMiddleware.func1at ./Getting-Started-with-Go-zero/gateway_login/gateway/middleware/login_and_auth.go:378  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:21229  0x0000000001969169 in github.com/zeromicro/go-zero/rest/handler.GunzipHandler.func1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/gunziphandler.go:26
10  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:2122
11  0x000000000196b3bf in github.com/zeromicro/go-zero/rest/handler.MaxBytesHandler.func2.1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/maxbyteshandler.go:24
12  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:2122
13  0x000000000196ba15 in github.com/zeromicro/go-zero/rest/handler.MetricHandler.func1.1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/metrichandler.go:21
14  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:2122
15  0x000000000196c243 in github.com/zeromicro/go-zero/rest/handler.RecoverHandler.func1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/recoverhandler.go:21
16  0x000000000089f52f in net/http.HandlerFunc.ServeHTTPat /usr/local/go/src/net/http/server.go:2122
17  0x000000000196d45c in github.com/zeromicro/go-zero/rest/handler.(*timeoutHandler).ServeHTTP.func1at ./go/pkg/mod/github.com/zeromicro/go-zero@v1.6.0/rest/handler/timeouthandler.go:82
18  0x0000000000471921 in runtime.goexitat /usr/local/go/src/runtime/asm_amd64.s:1598

在文件 zrpc/internal/clientinterceptors/tracinginterceptor.go 中调用了 metadata.NewOutgoingContext:

func startSpan(ctx context.Context, method, target string) (context.Context, trace.Span) {md, ok := metadata.FromOutgoingContext(ctx)if !ok {md = metadata.MD{}}tr := otel.Tracer(ztrace.TraceName)name, attr := ztrace.SpanInfo(method, target)ctx, span := tr.Start(ctx, name, trace.WithSpanKind(trace.SpanKindClient),trace.WithAttributes(attr...))ztrace.Inject(ctx, otel.GetTextMapPropagator(), &md)ctx = metadata.NewOutgoingContext(ctx, md)return ctx, span
}// UnaryTracingInterceptor returns a grpc.UnaryClientInterceptor for opentelemetry.
func UnaryTracingInterceptor(ctx context.Context, method string, req, reply any,cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error {ctx, span := startSpan(ctx, method, cc.Target())defer span.End()ztrace.MessageSent.Event(ctx, 1, req)err := invoker(ctx, method, req, reply, cc, opts...)ztrace.MessageReceived.Event(ctx, 1, reply)if err != nil {s, ok := status.FromError(err)if ok {span.SetStatus(codes.Error, s.Message())span.SetAttributes(ztrace.StatusCodeAttr(s.Code()))} else {span.SetStatus(codes.Error, err.Error())}return err}span.SetAttributes(ztrace.StatusCodeAttr(gcodes.OK))return nil
}

拦截器:

./zrpc/internal/rpcserver.go:		interceptors = append(interceptors, serverinterceptors.UnaryTracingInterceptor)
./zrpc/internal/client.go:		interceptors = append(interceptors, clientinterceptors.UnaryTracingInterceptor)

服务端代码:

//zrpc/internal/rpcserver.go
func (s *rpcServer) buildUnaryInterceptors() []grpc.UnaryServerInterceptor {var interceptors []grpc.UnaryServerInterceptorif s.middlewares.Trace {interceptors = append(interceptors, serverinterceptors.UnaryTracingInterceptor)}if s.middlewares.Recover {interceptors = append(interceptors, serverinterceptors.UnaryRecoverInterceptor)}if s.middlewares.Stat {interceptors = append(interceptors,serverinterceptors.UnaryStatInterceptor(s.metrics, s.middlewares.StatConf))}if s.middlewares.Prometheus {interceptors = append(interceptors, serverinterceptors.UnaryPrometheusInterceptor)}if s.middlewares.Breaker {interceptors = append(interceptors, serverinterceptors.UnaryBreakerInterceptor)}return append(interceptors, s.unaryInterceptors...)
}func (s *rpcServer) Start(register RegisterFn) error {lis, err := net.Listen("tcp", s.address)if err != nil {return err}unaryInterceptorOption := grpc.ChainUnaryInterceptor(s.buildUnaryInterceptors()...)streamInterceptorOption := grpc.ChainStreamInterceptor(s.buildStreamInterceptors()...)options := append(s.options, unaryInterceptorOption, streamInterceptorOption)server := grpc.NewServer(options...)register(server)// register the health check serviceif s.health != nil {grpc_health_v1.RegisterHealthServer(server, s.health)s.health.Resume()}s.healthManager.MarkReady()health.AddProbe(s.healthManager)// we need to make sure all others are wrapped up,// so we do graceful stop at shutdown phase instead of wrap up phasewaitForCalled := proc.AddShutdownListener(func() {if s.health != nil {s.health.Shutdown()}server.GracefulStop()})defer waitForCalled()return server.Serve(lis)
}

客户端代码:

//zrpc/internal/client.go
func (c *client) buildUnaryInterceptors(timeout time.Duration) []grpc.UnaryClientInterceptor {var interceptors []grpc.UnaryClientInterceptorif c.middlewares.Trace {interceptors = append(interceptors, clientinterceptors.UnaryTracingInterceptor)}if c.middlewares.Duration {interceptors = append(interceptors, clientinterceptors.DurationInterceptor)}if c.middlewares.Prometheus {interceptors = append(interceptors, clientinterceptors.PrometheusInterceptor)}if c.middlewares.Breaker {interceptors = append(interceptors, clientinterceptors.BreakerInterceptor)}if c.middlewares.Timeout {interceptors = append(interceptors, clientinterceptors.TimeoutInterceptor(timeout))}return interceptors
}func (c *client) buildDialOptions(opts ...ClientOption) []grpc.DialOption {var cliOpts ClientOptionsfor _, opt := range opts {opt(&cliOpts)}var options []grpc.DialOptionif !cliOpts.Secure {options = append([]grpc.DialOption(nil),grpc.WithTransportCredentials(insecure.NewCredentials()))}if !cliOpts.NonBlock {options = append(options, grpc.WithBlock())}options = append(options,grpc.WithChainUnaryInterceptor(c.buildUnaryInterceptors(cliOpts.Timeout)...),grpc.WithChainStreamInterceptor(c.buildStreamInterceptors()...),)return append(options, cliOpts.DialOptions...)
}func (c *client) dial(server string, opts ...ClientOption) error {options := c.buildDialOptions(opts...)timeCtx, cancel := context.WithTimeout(context.Background(), dialTimeout)defer cancel()conn, err := grpc.DialContext(timeCtx, server, options...)if err != nil {service := serverif errors.Is(err, context.DeadlineExceeded) {pos := strings.LastIndexByte(server, separator)// len(server) - 1 is the index of last charif 0 < pos && pos < len(server)-1 {service = server[pos+1:]}}return fmt.Errorf("rpc dial: %s, error: %s, make sure rpc service %q is already started",server, err.Error(), service)}c.conn = connreturn nil
}// NewClient returns a Client.
func NewClient(target string, middlewares ClientMiddlewaresConf, opts ...ClientOption) (Client, error) {cli := client{middlewares: middlewares,}svcCfg := fmt.Sprintf(`{"loadBalancingPolicy":"%s"}`, p2c.Name)balancerOpt := WithDialOption(grpc.WithDefaultServiceConfig(svcCfg))opts = append([]ClientOption{balancerOpt}, opts...)if err := cli.dial(target, opts...); err != nil {return nil, err}return &cli, nil
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/219572.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

推荐一款好用的包含表格识别的OCR网站

在当今数字化的时代&#xff0c;文字和表格识别已经成为了许多行业的关键技术。无论是处理大量的纸质文档&#xff0c;还是从网络上收集数据&#xff0c;OCR&#xff08;光学字符识别&#xff09;技术都扮演着重要的角色。然而&#xff0c;对于许多用户来说&#xff0c;OCR软件…

pta团体程序设计大赛——练习集(11-15)

L1-011 A-B 本题要求你计算A−B。不过麻烦的是&#xff0c;A和B都是字符串 —— 即从字符串A中把字符串B所包含的字符全删掉&#xff0c;剩下的字符组成的就是字符串A−B。 输入格式&#xff1a; 输入在2行中先后给出字符串A和B。两字符串的长度都不超过104&#xff0c;并且保证…

螺旋矩阵算法(leetcode第885题)

题目描述&#xff1a; 在 rows x cols 的网格上&#xff0c;你从单元格 (rStart, cStart) 面朝东面开始。网格的西北角位于第一行第一列&#xff0c;网格的东南角位于最后一行最后一列。你需要以顺时针按螺旋状行走&#xff0c;访问此网格中的每个位置。每当移动到网格的边界之…

GradNorm理解

主要参考这一篇&#xff0c;GradNorm&#xff1a;Gradient Normalization for Adaptive Loss Balancing in Deep Multitask Networks&#xff0c;梯度归一化_grad norm-CSDN博客 14:20-15:30 提前需要理解的概念 损失函数&#xff0c;衡量ypred与ytruth的差距。 Grad Loss定…

盲盒小程序如何盈利?创业新模式

当前&#xff0c;盲盒的影响力越来越大&#xff0c;深受年轻人的热爱&#xff0c;受众群体逐渐增加&#xff0c;盲盒的市场规模不断扩大。 在当下社交媒体时代&#xff0c;盲盒也转到了互联网上&#xff0c;根据网络的传播&#xff0c;盲盒也迎来了新一轮的发展&#xff0c;“…

python爬虫数据可视化

在Python中&#xff0c;你可以使用各种库来进行网络爬虫和数据可视化。以下是一个基本的例子&#xff0c;它使用requests库进行爬虫&#xff0c;BeautifulSoup进行HTML解析&#xff0c;pandas进行数据处理&#xff0c;和matplotlib进行数据可视化。 首先&#xff0c;我们需要安…

淘宝以图搜索商品接口 图片搜索商品列表接口 拍立淘接口

item_search_img-按图搜索淘宝商品&#xff08;拍立淘&#xff09; taobao.item_search_img 公共参数 名称类型必须描述keyString是调用key&#xff08;必须以GET方式拼接在URL中&#xff09;secretString是调用密钥api_nameString是API接口名称&#xff08;包括在请求地址中…

在服务器上配置jupyter notebook便于本地访问

文章目录 需求配置1. 安装jupyter2. 生成配置文件3. 设置登录密码并生成秘钥a. 打开服务器的终端b. 设置密码 4. 修改配置文件a. 进入配置文件所在的文件夹b. 编辑配置文件jupyter_notebook_config.pyc. 保存文件 5. 在服务器上生成jupyter访问地址 关注公众号&#xff1a;『 …

C# WinForm 跨线程访问控件

写在前面 在WinForm开发中&#xff0c;经常会碰到主线程代码运行过程中需要刷新窗体控件的情况&#xff0c;如果直接在其他线程中去操作窗体控件&#xff0c;这时会抛出线程间操作无效的异常信息&#xff0c;因为窗体控件是由主线程创建的&#xff0c;C#强制要求代码必须是线程…

SAP 标准GUI 中增加按钮时报错:EC181

今天在打一个note的时候&#xff0c;需要做一些手动的调整&#xff0c;其中的步骤就需要我去在标准的GUI STATUS 增加按钮 我在进入编辑模式的时候&#xff0c;直接去插入的时候&#xff0c;始终报错如下&#xff1a; Function code xxxx has not been assigned to a functio…

使用matlab制作声音采样率转换、播放以及显示的界面

利用matlab做一个声音采样率转换、播放以及显示的界面 大抵流程&#xff1a; 图形界面创建&#xff1a;使用figure函数创建名为“声音采样率转换”的图形界面&#xff0c;并设置了其位置和大小。 按钮和文本框&#xff1a;使用uicontrol函数创建了选择音频文件的按钮、显示当前…

js基础之事件监听案例入门

事件绑定 代码 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title> </head&…

【IDEA】关于快捷键行注释时会从行首开始注释

前言 每次在使用IDEA写代码时&#xff0c;用快捷键进行行注释的时候&#xff0c;//会处于行首位置 但是我们想要的是这种注释效果 修改 IDEA中打开settings 找到Editor - Code Style- Java - 找到Code Genneration&#xff0c;取消勾选Line comment at first column&#x…

汽车内饰设计开发流程(入门基础)

1 开发流程简介 2 汽车内饰的子系统&#xff08;分类&#xff09; 1 软内饰&#xff08;顶棚、地毯、座椅&#xff09; 2 硬内饰&#xff08;仪表板、副仪表板护、A柱饰板、B柱饰板、C柱饰板、门槛、侧围饰板、背门饰板&#xff09; 3内外饰板的分类&#xff1a;功能件和装饰…

Linux的重定向

Linux中的重定向是将程序的输入流或输出流从默认的位置改变到指定的位置。可以使用特殊的符号来实现重定向操作。&#xff08;文中command代表命令&#xff09; &#xff08;1&#xff09;重定向命令列表 命令 说明 command > file …

第16章 网络io与io多路复用select/pool/epool

第16.1节 写一个服务端代码 服务端代码 #include <stdio.h> #include <errno.h> #include <string.h> #include <unistd.h> #include <sys/socket.h> #include <netinet/in.h>#include <fcntl.h>int main() {//openint sockfd sock…

ORACLE DG 三种保护模式

– Maximum protection(最大保护模式) – Maximum availability(最大可用模式) – Maximum performance(最大性能模式) 查看dg是什么模式的 select database_role,protection_mode,protection_level from v$database; 在Maximum protection下&#xff0c; 可以保证从库和主库数…

Java集合转树结构(treeList)

java list集合转树结构&#xff08;treeList&#xff09; 我们在实际开发中&#xff0c;肯定会用到树结构&#xff0c;如部门树、菜单树等等。Java后端利用递归思路进行构建树形结构数据&#xff0c;返回给前端&#xff0c;能以下拉菜单等形式进行展示。今天&#xff0c;咱们就…

【开题报告】基于SpringBoot的影视作品网站的设计与实现

1.项目背景 影视作品网站是一个非常受欢迎的网络平台&#xff0c;它为用户提供了方便快捷的电影、电视剧、综艺等各类影视作品的信息浏览、搜索、点播和讨论交流功能。在这个平台上&#xff0c;用户可以方便地查找自己感兴趣的影视作品&#xff0c;并进行在线观看或者与其他用…

考试的最大困扰度

说在前面 &#x1f388;不知道大家对于算法的学习是一个怎样的心态呢&#xff1f;为了面试还是因为兴趣&#xff1f;不管是出于什么原因&#xff0c;算法学习需要持续保持。 1、题目描述 一位老师正在出一场由 n 道判断题构成的考试&#xff0c;每道题的答案为 true &#xff…