Golang Kratos中间件,访问操作

huangapple go评论87阅读模式
英文:

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())
}

huangapple
  • 本文由 发表于 2023年2月26日 21:37:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/75572355.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定