Link Search Menu Expand Document

Extracting the HTTP path pattern for a request

It is often interesting to know what HTTP path pattern was matched for a specific request, for example for metrics. This article explains how to extract the HTTP path pattern from the request context.

Get HTTP Path pattern

  1. Define the HTTP path in the proto annotation. For example:
syntax = "proto3";
option go_package = "github.com/grpc-ecosystem/grpc-gateway/v2/examples/internal/proto/examplepb";
package grpc.gateway.examples.internal.proto.examplepb;

import "google/api/annotations.proto";

service LoginService {
  rpc Login (LoginRequest) returns (LoginReply) {
    option (google.api.http) = {
        post: "/v1/example/login"
        body: "*"
    };
  }
}

message LoginRequest {}

message LoginReply {}
  1. At runtime, get the HTTP path pattern from the annotated context, for example using the WithMetadata function. You can pass data to your backend by adding them to the gRPC metadata or push them to a metrics server.
mux := runtime.NewServeMux(
	runtime.WithMetadata(func(ctx context.Context, r *http.Request) metadata.MD {
		md := make(map[string]string)
		if method, ok := runtime.RPCMethod(ctx); ok {
			md["method"] = method // /grpc.gateway.examples.internal.proto.examplepb.LoginService/Login
		}
		if pattern, ok := runtime.HTTPPathPattern(ctx); ok {
			md["pattern"] = pattern // /v1/example/login
		}
		return metadata.New(md)
	}),
)