英文:
Golang Kratos middleware, access operation
问题
我们正在使用Kratos来开发我们的golang grpc/http API。我正在尝试实现一个中间件,下面是我传递的ServerOptions。
var opts = []http.ServerOption{
http.Middleware(
metadata.Server(metadata.WithPropagatedPrefix("client-id", "authorization")),
selector.Server(CheckForCache(cacheHandler)).Match(func(ctx context.Context, operation string) bool {
// 在这里进行其他逻辑检查路径
return true
}).Build(),
GetUserFromToken(c.ClientId),
recovery.Recovery(),
),
}
中间件被正确调用了。我想在我的CheckForCache
函数中访问operation
以进行一些逻辑处理。我该如何将它作为参数传递进去?或者是否有其他方法可以在我的CheckForCache
函数中访问operation
?
以下是我的中间件函数代码。
func CheckForCache(cacheHandler *redis.RedisCache) middleware.Middleware {
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
// TODO: 在这里访问operation
// operation的示例:/api.my_package.MyService/MyFunction
return handler(ctx, req)
}
}
}
英文:
We are using Kratos for development of our grpc/http APIs in golang. I am trying to implement a middleware and below are the ServerOptions that I am passing.
var opts = []http.ServerOption{
http.Middleware(
metadata.Server(metadata.WithPropagatedPrefix("client-id", "authorization")),
selector.Server(CheckForCache(cacheHandler)).Match(func(ctx context.Context, operation string) bool {
// other logic here to check for path
return true
}).Build(),
GetUserFromToken(c.ClientId),
recovery.Recovery(),
),
}
The middleware is getting called properly. I want to access the operation inside my CheckForCache
function for some logic. How can I pass it there as a parameter? Or is there other way I can access the operation in my CheckForCache
function.
Below is my code for the middleware function.
func CheckForCache(cacheHandler *redis.RedisCache) middleware.Middleware {
return func(handler middleware.Handler) middleware.Handler {
return func(ctx context.Context, req interface{}) (reply interface{}, err error) {
// TODO: Access operation here
// example of operation: /api.my_package.MyService/MyFunction
return handler(ctx, req)
}
}}
答案1
得分: 1
我可以通过transport
包来实现这个功能。
以下是相同功能的代码。
if info, ok := transport.FromServerContext(ctx); ok {
fmt.Println("OPERATION: ", info.Operation())
}
英文:
I was able to achieve this by the transport
package.
Below is the code for the same.
if info, ok := transport.FromServerContext(ctx); ok {
fmt.Println("OPERATION: ", info.Operation())
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论