10 "github.com/golang/protobuf/proto"
11 "google.golang.org/grpc/codes"
12 "google.golang.org/grpc/metadata"
13 "google.golang.org/grpc/status"
16 // A HandlerFunc handles a specific pair of path pattern and HTTP method.
17 type HandlerFunc func(w http.ResponseWriter, r *http.Request, pathParams map[string]string)
19 // ServeMux is a request multiplexer for grpc-gateway.
20 // It matches http requests to patterns and invokes the corresponding handler.
21 type ServeMux struct {
22 // handlers maps HTTP method to a list of handlers.
23 handlers map[string][]handler
24 forwardResponseOptions []func(context.Context, http.ResponseWriter, proto.Message) error
25 marshalers marshalerRegistry
26 incomingHeaderMatcher HeaderMatcherFunc
27 outgoingHeaderMatcher HeaderMatcherFunc
28 metadataAnnotators []func(context.Context, *http.Request) metadata.MD
29 protoErrorHandler ProtoErrorHandlerFunc
30 disablePathLengthFallback bool
33 // ServeMuxOption is an option that can be given to a ServeMux on construction.
34 type ServeMuxOption func(*ServeMux)
36 // WithForwardResponseOption returns a ServeMuxOption representing the forwardResponseOption.
38 // forwardResponseOption is an option that will be called on the relevant context.Context,
39 // http.ResponseWriter, and proto.Message before every forwarded response.
41 // The message may be nil in the case where just a header is being sent.
42 func WithForwardResponseOption(forwardResponseOption func(context.Context, http.ResponseWriter, proto.Message) error) ServeMuxOption {
43 return func(serveMux *ServeMux) {
44 serveMux.forwardResponseOptions = append(serveMux.forwardResponseOptions, forwardResponseOption)
48 // HeaderMatcherFunc checks whether a header key should be forwarded to/from gRPC context.
49 type HeaderMatcherFunc func(string) (string, bool)
51 // DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header
52 // keys (as specified by the IANA) to gRPC context with grpcgateway- prefix. HTTP headers that start with
53 // 'Grpc-Metadata-' are mapped to gRPC metadata after removing prefix 'Grpc-Metadata-'.
54 func DefaultHeaderMatcher(key string) (string, bool) {
55 key = textproto.CanonicalMIMEHeaderKey(key)
56 if isPermanentHTTPHeader(key) {
57 return MetadataPrefix + key, true
58 } else if strings.HasPrefix(key, MetadataHeaderPrefix) {
59 return key[len(MetadataHeaderPrefix):], true
64 // WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway.
66 // This matcher will be called with each header in http.Request. If matcher returns true, that header will be
67 // passed to gRPC context. To transform the header before passing to gRPC context, matcher should return modified header.
68 func WithIncomingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption {
69 return func(mux *ServeMux) {
70 mux.incomingHeaderMatcher = fn
74 // WithOutgoingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway.
76 // This matcher will be called with each header in response header metadata. If matcher returns true, that header will be
77 // passed to http response returned from gateway. To transform the header before passing to response,
78 // matcher should return modified header.
79 func WithOutgoingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption {
80 return func(mux *ServeMux) {
81 mux.outgoingHeaderMatcher = fn
85 // WithMetadata returns a ServeMuxOption for passing metadata to a gRPC context.
87 // This can be used by services that need to read from http.Request and modify gRPC context. A common use case
88 // is reading token from cookie and adding it in gRPC context.
89 func WithMetadata(annotator func(context.Context, *http.Request) metadata.MD) ServeMuxOption {
90 return func(serveMux *ServeMux) {
91 serveMux.metadataAnnotators = append(serveMux.metadataAnnotators, annotator)
95 // WithProtoErrorHandler returns a ServeMuxOption for passing metadata to a gRPC context.
97 // This can be used to handle an error as general proto message defined by gRPC.
98 // The response including body and status is not backward compatible with the default error handler.
99 // When this option is used, HTTPError and OtherErrorHandler are overwritten on initialization.
100 func WithProtoErrorHandler(fn ProtoErrorHandlerFunc) ServeMuxOption {
101 return func(serveMux *ServeMux) {
102 serveMux.protoErrorHandler = fn
106 // WithDisablePathLengthFallback returns a ServeMuxOption for disable path length fallback.
107 func WithDisablePathLengthFallback() ServeMuxOption {
108 return func(serveMux *ServeMux) {
109 serveMux.disablePathLengthFallback = true
113 // NewServeMux returns a new ServeMux whose internal mapping is empty.
114 func NewServeMux(opts ...ServeMuxOption) *ServeMux {
115 serveMux := &ServeMux{
116 handlers: make(map[string][]handler),
117 forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0),
118 marshalers: makeMarshalerMIMERegistry(),
121 for _, opt := range opts {
125 if serveMux.protoErrorHandler != nil {
126 HTTPError = serveMux.protoErrorHandler
127 // OtherErrorHandler is no longer used when protoErrorHandler is set.
128 // Overwritten by a special error handler to return Unknown.
129 OtherErrorHandler = func(w http.ResponseWriter, r *http.Request, _ string, _ int) {
130 ctx := context.Background()
131 _, outboundMarshaler := MarshalerForRequest(serveMux, r)
132 sterr := status.Error(codes.Unknown, "unexpected use of OtherErrorHandler")
133 serveMux.protoErrorHandler(ctx, serveMux, outboundMarshaler, w, r, sterr)
137 if serveMux.incomingHeaderMatcher == nil {
138 serveMux.incomingHeaderMatcher = DefaultHeaderMatcher
141 if serveMux.outgoingHeaderMatcher == nil {
142 serveMux.outgoingHeaderMatcher = func(key string) (string, bool) {
143 return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true
150 // Handle associates "h" to the pair of HTTP method and path pattern.
151 func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) {
152 s.handlers[meth] = append(s.handlers[meth], handler{pat: pat, h: h})
155 // ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.Path.
156 func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) {
160 if !strings.HasPrefix(path, "/") {
161 if s.protoErrorHandler != nil {
162 _, outboundMarshaler := MarshalerForRequest(s, r)
163 sterr := status.Error(codes.InvalidArgument, http.StatusText(http.StatusBadRequest))
164 s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
166 OtherErrorHandler(w, r, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
171 components := strings.Split(path[1:], "/")
174 if idx := strings.LastIndex(components[l-1], ":"); idx == 0 {
175 if s.protoErrorHandler != nil {
176 _, outboundMarshaler := MarshalerForRequest(s, r)
177 sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented))
178 s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
180 OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound)
185 components[l-1], verb = c[:idx], c[idx+1:]
188 if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && s.isPathLengthFallback(r) {
189 r.Method = strings.ToUpper(override)
190 if err := r.ParseForm(); err != nil {
191 if s.protoErrorHandler != nil {
192 _, outboundMarshaler := MarshalerForRequest(s, r)
193 sterr := status.Error(codes.InvalidArgument, err.Error())
194 s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
196 OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest)
201 for _, h := range s.handlers[r.Method] {
202 pathParams, err := h.pat.Match(components, verb)
206 h.h(w, r, pathParams)
210 // lookup other methods to handle fallback from GET to POST and
211 // to determine if it is MethodNotAllowed or NotFound.
212 for m, handlers := range s.handlers {
216 for _, h := range handlers {
217 pathParams, err := h.pat.Match(components, verb)
221 // X-HTTP-Method-Override is optional. Always allow fallback to POST.
222 if s.isPathLengthFallback(r) {
223 if err := r.ParseForm(); err != nil {
224 if s.protoErrorHandler != nil {
225 _, outboundMarshaler := MarshalerForRequest(s, r)
226 sterr := status.Error(codes.InvalidArgument, err.Error())
227 s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
229 OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest)
233 h.h(w, r, pathParams)
236 if s.protoErrorHandler != nil {
237 _, outboundMarshaler := MarshalerForRequest(s, r)
238 sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusMethodNotAllowed))
239 s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
241 OtherErrorHandler(w, r, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed)
247 if s.protoErrorHandler != nil {
248 _, outboundMarshaler := MarshalerForRequest(s, r)
249 sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented))
250 s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr)
252 OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound)
256 // GetForwardResponseOptions returns the ForwardResponseOptions associated with this ServeMux.
257 func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.ResponseWriter, proto.Message) error {
258 return s.forwardResponseOptions
261 func (s *ServeMux) isPathLengthFallback(r *http.Request) bool {
262 return !s.disablePathLengthFallback && r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded"
265 type handler struct {