提取用户请求中路径的方法在golang grpc-gateway中
时间:2024-03-15
浏览: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知识!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
11.29
热门专题
