Home > Software design >  How to extract path from user request in golang grpc-gateway
How to extract path from user request in golang grpc-gateway

Time:10-26

i have a question. Is it possible to extract via metadata path from user request.

Here i have my proto file with defined method.

  rpc AllPath(google.protobuf.Empty) returns (google.protobuf.Empty) {
    option (google.api.http) = {
      get: "/*",
    };
  }
  rpc Auth(google.protobuf.Empty) returns (TokenRender) {
    option (google.api.http) = {
      get: "/auth"
    };
  }
}

In AllPath function in my server file im using something like this, found on grpc-gateway ecosystem website.

    path := make(map[string]string)
    if pattern, ok := runtime.HTTPPathPattern(ctx); ok {
        path["pattern"] = pattern // /v1/example/login
    }
    fmt.Printf("Current path is: %v", path["pattern"])

but my current pattern/path is like i defined in proto file: Current path is: /*

If anyone have idea how to deal with this thing i would appreciate it :)

Best, Kacper

CodePudding user response:

gRPC-Gateway passes various bits of information from the originating HTTP request via gRPC metadata. I don't believe the raw path is supplied, however. It is still possible to get the path passed through by registering a metadata annotator.

When calling github.com/grpc-ecosystem/grpc-gateway/v2/runtime.NewServeMux(), leverage the WithMetadata option func:

mux := runtime.NewServeMux(runtime.WithMetadata(func(_ context.Context, req *http.Request) metadata.MD {
    return metadata.New(map[string]string{
        "grpcgateway-http-path": req.URL.Path,
    })
}))

Then in your gRPC service implementation, you can retrieve the value via the incoming context:

func (s *server) AllPath(ctx context.Context, _ *emptypb.Empty) (*emptypb.Empty, error) {
    md, _ := metadata.FromIncomingContext(ctx)
    log.Printf("path: %s", md["grpcgateway-http-path"][0])
    return &emptypb.Empty{}, nil
}

When hitting, e.g. /foo, this should log:

2022/10/25 15:31:42 path: /foo
  • Related