英文:
How can I pass the origin from gin gonic to a gRPC microservice
问题
我正在编写一个支持多个来源的微服务(这些来源定义了要连接的数据库)。为了做到这一点,我需要获取来源信息。使用gin作为服务器负责验证来源,而rpc微服务不验证任何内容。我唯一遗漏的是如何将这些元数据传递给上下文中的rpc服务。
我尽量简化了这个想法,实际情况要复杂得多,并且有多个值要传递。将所有这些内容传递给所有函数是不可行的,因为这会产生太多的开销。
Gin服务器
func OriginMiddleware() gin.HandlerFunc {
return func(context *gin.Context) {
origin := context.GetHeader("origin")
// 将origin添加到上下文中
context.Next()
}
}
func main(){
... // 设置grpc等
r.Use(OriginMiddleware())
r.POST("/login", User.Login)
r.GET("/getUser", User.Get)
... // 其他许多端点
r.Run("localhost:8080")
}
微服务
func OriginInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
origin := ctx.Value("origin")
fmt.Println(origin)
... // 获取或创建数据库连接等操作
return handler(ctx, req)
}
}
func main() {
... // 设置
s := grpc.NewServer(grpc.UnaryInterceptor(MongoInterceptor()))
UserPB.RegisterUserServiceServer(s, &server{})
... // 启动服务
}
我尝试过的方法
- 重写gin上下文似乎是不可能的
- 使用
.Set
只在"gin"服务器内部有效,但在发送到grpc时所有值都丢失了
英文:
I'm writing a microservice that supports multiple origins (which then define what database to connect to). In order to do that I need for example the origin. The server with gin is responsible to validate the origin, the rpc microservice does not validate anything. The only point that I am missing is how to pass this metadata to the rpc service inside the context.
I simplified the idea as much as I could, the real case is way more complex, and there is more than 1 value to pass. Passing all those things to all functions is out of discussion, as it would generate way too much overhead
Gin server
func OriginMiddleware() gin.HandlerFunc {
return func(context *gin.Context) {
origin := context.GetHeader("origin")
// add origin to the context
context.Next()
}
}
func main(){
... // setup grpc etc
r.Use(OriginMiddleware())
r.POST("/login", User.Login)
r.GET("/getUser", User.Get)
... // many other endpoints
r.Run("localhost:8080")
}
Microservice
func OriginInterceptor() grpc.UnaryServerInterceptor {
return func(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (resp interface{}, err error) {
origin := ctx.Value("origin")
fmt.Println(origin)
... // get or create db connection whatsoever
return handler(ctx, req)
}
}
func main() {
... // setup
s := grpc.NewServer(grpc.UnaryInterceptor(MongoInterceptor()))
UserPB.RegisterUserServiceServer(s, &server{})
... // serve
}
What I've been trying
- Overwriting the gin context doesn't seem possible
- Using
.Set
works only as long as it's inside the "gin" server, but all values are lost when sent to grpc
答案1
得分: 1
我找到了一个可行的解决方案,但并不是最干净的。欢迎提出改进和批评意见!
func ToGrpcContext(ctx *gin.Context) context.Context {
res := make(map[string]string)
for key, value := range ctx.Keys {
switch v := value.(type) {
case string:
res[key] = v
}
}
return metadata.NewOutgoingContext(ctx, metadata.New(res))
}
每次调用任何grpc函数时,我都会使用这个辅助函数包装上下文,例如:
user, err := UserPB.GetUser(ToGrpcContext(ctx), &UserPB.GetUserInput{...})
英文:
I found a solution that works, but it's not the cleanest. Improvements and critics are well accepted!
func ToGrpcContext(ctx *gin.Context) context.Context {
res := make(map[string]string)
for key, value := range ctx.Keys {
switch v := value.(type) {
case string:
res[key] = v
}
}
return metadata.NewOutgoingContext(ctx, metadata.New(res))
}
Each time I call any grpc function, I wrap the context with this helper function, like:
user, err := UserPB.GetUser(ToGrpcContext(ctx), &UserPB.GetUserInput{...})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论