Golang Kratos middleware, access operation

320 Views Asked by At

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

There are 1 best solutions below

0
On

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