登录
首页 >  Golang >  Go问答

提取用户请求中路径的方法在golang grpc-gateway中

来源:stackoverflow

时间:2024-03-15 13:36:27 442浏览 收藏

在IT行业这个发展更新速度很快的行业,只有不停止的学习,才不会被行业所淘汰。如果你是Golang学习者,那么本文《提取用户请求中路径的方法在golang grpc-gateway中》就很适合你!本篇内容主要包括##content_title##,希望对大家的知识积累有所帮助,助力实战开发!

问题内容

我有一个问题。是否可以通过元数据路径从用户请求中提取。

这里我有我的原型文件和定义的方法。

rpc allpath(google.protobuf.empty) returns (google.protobuf.empty) {
    option (google.api.http) = {
      get: "/*",
    };
  }
  rpc auth(google.protobuf.empty) returns (tokenrender) {
    option (google.api.http) = {
      get: "/auth"
    };
  }
}

在我的服务器文件中的 allpath 函数中,我使用类似的东西,可以在 grpc-gateway 生态系统网站上找到。

path := make(map[string]string)
    if pattern, ok := runtime.HTTPPathPattern(ctx); ok {
        path["pattern"] = pattern // /v1/example/login
    }
    fmt.Printf("Current path is: %v", path["pattern"])

但我当前的模式/路径就像我在原型文件中定义的那样:当前路径是:/*

如果有人知道如何处理这件事,我将不胜感激:)

最好,卡佩尔


正确答案


grpc-gateway 通过 grpc 元数据传递来自原始 http 请求的各种信息。但是,我不相信提供了原始路径。仍然可以通过注册元数据注释器来获取经过的路径。

调用 github.com/grpc-ecosystem/grpc-gateway/v2/runtime.newservemux() 时,利用 withmetadata 选项函数:

mux := runtime.newservemux(runtime.withmetadata(func(_ context.context, req *http.request) metadata.md {
    return metadata.new(map[string]string{
        "grpcgateway-http-path": req.url.path,
    })
}))

然后在 grpc 服务实现中,您可以通过传入上下文检索值:

func (s *server) allpath(ctx context.context, _ *emptypb.empty) (*emptypb.empty, error) {
    md, _ := metadata.fromincomingcontext(ctx)
    log.printf("path: %s", md["grpcgateway-http-path"][0])
    return &emptypb.empty{}, nil
}

击中时,例如/foo,这应该记录:

2022/10/25 15:31:42 path: /foo

好了,本文到此结束,带大家了解了《提取用户请求中路径的方法在golang grpc-gateway中》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多Golang知识!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>