如何在Golang Kratos中间件的CheckForCache函数中获取operation?
在Kratos中间件中获取Operation的方案
有两种可行方案可以在CheckForCache中间件里拿到目标operation:
方案一:通过Selector的Match函数注入Context
利用Selector的Match函数能直接获取operation的特性,把它存入请求上下文,再在中间件里取出使用:
修改Selector配置
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 { // 将operation存入context ctx = context.WithValue(ctx, "operation", operation) // 保留原有匹配逻辑 return true }).Build(), GetUserFromToken(c.ClientId), recovery.Recovery(), ), }
修改CheckForCache函数
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) { // 从context中取出operation if operation, ok := ctx.Value("operation").(string); ok { // 这里就可以用operation做业务逻辑了 // 比如打印或传入缓存处理逻辑 } return handler(ctx, req) } }}
方案二:使用Kratos内置方法提取(推荐)
Kratos的请求上下文本身就携带了transport信息,其中包含operation,直接通过官方API提取更规范:
修改CheckForCache函数(无需改动Selector)
import "github.com/go-kratos/kratos/v2/transport" 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) { // 从context中获取transport实例 if tr, ok := transport.FromServerContext(ctx); ok { operation := tr.Operation() // 这里直接使用operation即可,格式就是你需要的/api.my_package.MyService/MyFunction } return handler(ctx, req) } }}
推荐用第二种方案,不需要额外注入逻辑,完全依赖Kratos框架提供的能力,更稳定也更符合框架设计思路。
内容的提问来源于stack exchange,提问作者XCEPTION
相关产品推荐
相关产品推荐

