| 1 |
package runtime |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"net/http" |
| 6 |
"net/textproto" |
| 7 |
"strings" |
| 8 |
|
| 9 |
"github.com/golang/protobuf/proto" |
| 10 |
"golang.org/x/net/context" |
| 11 |
"google.golang.org/grpc/codes" |
| 12 |
"google.golang.org/grpc/metadata" |
| 13 |
"google.golang.org/grpc/status" |
| 14 |
) |
| 15 |
|
| 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) |
| 18 |
|
| 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 |
metadataAnnotator func(context.Context, *http.Request) metadata.MD |
| 29 |
protoErrorHandler ProtoErrorHandlerFunc |
| 30 |
} |
| 31 |
|
| 32 |
// ServeMuxOption is an option that can be given to a ServeMux on construction. |
| 33 |
type ServeMuxOption func(*ServeMux) |
| 34 |
|
| 35 |
// WithForwardResponseOption returns a ServeMuxOption representing the forwardResponseOption. |
| 36 |
// |
| 37 |
// forwardResponseOption is an option that will be called on the relevant context.Context, |
| 38 |
// http.ResponseWriter, and proto.Message before every forwarded response. |
| 39 |
// |
| 40 |
// The message may be nil in the case where just a header is being sent. |
| 41 |
func WithForwardResponseOption(forwardResponseOption func(context.Context, http.ResponseWriter, proto.Message) error) ServeMuxOption { |
| 42 |
return func(serveMux *ServeMux) { |
| 43 |
serveMux.forwardResponseOptions = append(serveMux.forwardResponseOptions, forwardResponseOption) |
| 44 |
} |
| 45 |
} |
| 46 |
|
| 47 |
// HeaderMatcherFunc checks whether a header key should be forwarded to/from gRPC context. |
| 48 |
type HeaderMatcherFunc func(string) (string, bool) |
| 49 |
|
| 50 |
// DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header |
| 51 |
// keys (as specified by the IANA) to gRPC context with grpcgateway- prefix. HTTP headers that start with |
| 52 |
// 'Grpc-Metadata-' are mapped to gRPC metadata after removing prefix 'Grpc-Metadata-'. |
| 53 |
func DefaultHeaderMatcher(key string) (string, bool) { |
| 54 |
key = textproto.CanonicalMIMEHeaderKey(key) |
| 55 |
if isPermanentHTTPHeader(key) { |
| 56 |
return MetadataPrefix + key, true |
| 57 |
} else if strings.HasPrefix(key, MetadataHeaderPrefix) { |
| 58 |
return key[len(MetadataHeaderPrefix):], true |
| 59 |
} |
| 60 |
return "", false |
| 61 |
} |
| 62 |
|
| 63 |
// WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway. |
| 64 |
// |
| 65 |
// This matcher will be called with each header in http.Request. If matcher returns true, that header will be |
| 66 |
// passed to gRPC context. To transform the header before passing to gRPC context, matcher should return modified header. |
| 67 |
func WithIncomingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption { |
| 68 |
return func(mux *ServeMux) { |
| 69 |
mux.incomingHeaderMatcher = fn |
| 70 |
} |
| 71 |
} |
| 72 |
|
| 73 |
// WithOutgoingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway. |
| 74 |
// |
| 75 |
// This matcher will be called with each header in response header metadata. If matcher returns true, that header will be |
| 76 |
// passed to http response returned from gateway. To transform the header before passing to response, |
| 77 |
// matcher should return modified header. |
| 78 |
func WithOutgoingHeaderMatcher(fn HeaderMatcherFunc) ServeMuxOption { |
| 79 |
return func(mux *ServeMux) { |
| 80 |
mux.outgoingHeaderMatcher = fn |
| 81 |
} |
| 82 |
} |
| 83 |
|
| 84 |
// WithMetadata returns a ServeMuxOption for passing metadata to a gRPC context. |
| 85 |
// |
| 86 |
// This can be used by services that need to read from http.Request and modify gRPC context. A common use case |
| 87 |
// is reading token from cookie and adding it in gRPC context. |
| 88 |
func WithMetadata(annotator func(context.Context, *http.Request) metadata.MD) ServeMuxOption { |
| 89 |
return func(serveMux *ServeMux) { |
| 90 |
serveMux.metadataAnnotator = annotator |
| 91 |
} |
| 92 |
} |
| 93 |
|
| 94 |
// WithProtoErrorHandler returns a ServeMuxOption for passing metadata to a gRPC context. |
| 95 |
// |
| 96 |
// This can be used to handle an error as general proto message defined by gRPC. |
| 97 |
// The response including body and status is not backward compatible with the default error handler. |
| 98 |
// When this option is used, HTTPError and OtherErrorHandler are overwritten on initialization. |
| 99 |
func WithProtoErrorHandler(fn ProtoErrorHandlerFunc) ServeMuxOption { |
| 100 |
return func(serveMux *ServeMux) { |
| 101 |
serveMux.protoErrorHandler = fn |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
// NewServeMux returns a new ServeMux whose internal mapping is empty. |
| 106 |
func NewServeMux(opts ...ServeMuxOption) *ServeMux { |
| 107 |
serveMux := &ServeMux{ |
| 108 |
handlers: make(map[string][]handler), |
| 109 |
forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0), |
| 110 |
marshalers: makeMarshalerMIMERegistry(), |
| 111 |
} |
| 112 |
|
| 113 |
for _, opt := range opts { |
| 114 |
opt(serveMux) |
| 115 |
} |
| 116 |
|
| 117 |
if serveMux.protoErrorHandler != nil { |
| 118 |
HTTPError = serveMux.protoErrorHandler |
| 119 |
// OtherErrorHandler is no longer used when protoErrorHandler is set. |
| 120 |
// Overwritten by a special error handler to return Unknown. |
| 121 |
OtherErrorHandler = func(w http.ResponseWriter, r *http.Request, _ string, _ int) { |
| 122 |
ctx := context.Background() |
| 123 |
_, outboundMarshaler := MarshalerForRequest(serveMux, r) |
| 124 |
sterr := status.Error(codes.Unknown, "unexpected use of OtherErrorHandler") |
| 125 |
serveMux.protoErrorHandler(ctx, serveMux, outboundMarshaler, w, r, sterr) |
| 126 |
} |
| 127 |
} |
| 128 |
|
| 129 |
if serveMux.incomingHeaderMatcher == nil { |
| 130 |
serveMux.incomingHeaderMatcher = DefaultHeaderMatcher |
| 131 |
} |
| 132 |
|
| 133 |
if serveMux.outgoingHeaderMatcher == nil { |
| 134 |
serveMux.outgoingHeaderMatcher = func(key string) (string, bool) { |
| 135 |
return fmt.Sprintf("%s%s", MetadataHeaderPrefix, key), true |
| 136 |
} |
| 137 |
} |
| 138 |
|
| 139 |
return serveMux |
| 140 |
} |
| 141 |
|
| 142 |
// Handle associates "h" to the pair of HTTP method and path pattern. |
| 143 |
func (s *ServeMux) Handle(meth string, pat Pattern, h HandlerFunc) { |
| 144 |
s.handlers[meth] = append(s.handlers[meth], handler{pat: pat, h: h}) |
| 145 |
} |
| 146 |
|
| 147 |
// ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.Path. |
| 148 |
func (s *ServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| 149 |
ctx := r.Context() |
| 150 |
|
| 151 |
path := r.URL.Path |
| 152 |
if !strings.HasPrefix(path, "/") { |
| 153 |
if s.protoErrorHandler != nil { |
| 154 |
_, outboundMarshaler := MarshalerForRequest(s, r) |
| 155 |
sterr := status.Error(codes.InvalidArgument, http.StatusText(http.StatusBadRequest)) |
| 156 |
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) |
| 157 |
} else { |
| 158 |
OtherErrorHandler(w, r, http.StatusText(http.StatusBadRequest), http.StatusBadRequest) |
| 159 |
} |
| 160 |
return |
| 161 |
} |
| 162 |
|
| 163 |
components := strings.Split(path[1:], "/") |
| 164 |
l := len(components) |
| 165 |
var verb string |
| 166 |
if idx := strings.LastIndex(components[l-1], ":"); idx == 0 { |
| 167 |
if s.protoErrorHandler != nil { |
| 168 |
_, outboundMarshaler := MarshalerForRequest(s, r) |
| 169 |
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented)) |
| 170 |
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) |
| 171 |
} else { |
| 172 |
OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound) |
| 173 |
} |
| 174 |
return |
| 175 |
} else if idx > 0 { |
| 176 |
c := components[l-1] |
| 177 |
components[l-1], verb = c[:idx], c[idx+1:] |
| 178 |
} |
| 179 |
|
| 180 |
if override := r.Header.Get("X-HTTP-Method-Override"); override != "" && isPathLengthFallback(r) { |
| 181 |
r.Method = strings.ToUpper(override) |
| 182 |
if err := r.ParseForm(); err != nil { |
| 183 |
if s.protoErrorHandler != nil { |
| 184 |
_, outboundMarshaler := MarshalerForRequest(s, r) |
| 185 |
sterr := status.Error(codes.InvalidArgument, err.Error()) |
| 186 |
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) |
| 187 |
} else { |
| 188 |
OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest) |
| 189 |
} |
| 190 |
return |
| 191 |
} |
| 192 |
} |
| 193 |
for _, h := range s.handlers[r.Method] { |
| 194 |
pathParams, err := h.pat.Match(components, verb) |
| 195 |
if err != nil { |
| 196 |
continue |
| 197 |
} |
| 198 |
h.h(w, r, pathParams) |
| 199 |
return |
| 200 |
} |
| 201 |
|
| 202 |
// lookup other methods to handle fallback from GET to POST and |
| 203 |
// to determine if it is MethodNotAllowed or NotFound. |
| 204 |
for m, handlers := range s.handlers { |
| 205 |
if m == r.Method { |
| 206 |
continue |
| 207 |
} |
| 208 |
for _, h := range handlers { |
| 209 |
pathParams, err := h.pat.Match(components, verb) |
| 210 |
if err != nil { |
| 211 |
continue |
| 212 |
} |
| 213 |
// X-HTTP-Method-Override is optional. Always allow fallback to POST. |
| 214 |
if isPathLengthFallback(r) { |
| 215 |
if err := r.ParseForm(); err != nil { |
| 216 |
if s.protoErrorHandler != nil { |
| 217 |
_, outboundMarshaler := MarshalerForRequest(s, r) |
| 218 |
sterr := status.Error(codes.InvalidArgument, err.Error()) |
| 219 |
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) |
| 220 |
} else { |
| 221 |
OtherErrorHandler(w, r, err.Error(), http.StatusBadRequest) |
| 222 |
} |
| 223 |
return |
| 224 |
} |
| 225 |
h.h(w, r, pathParams) |
| 226 |
return |
| 227 |
} |
| 228 |
if s.protoErrorHandler != nil { |
| 229 |
_, outboundMarshaler := MarshalerForRequest(s, r) |
| 230 |
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusMethodNotAllowed)) |
| 231 |
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) |
| 232 |
} else { |
| 233 |
OtherErrorHandler(w, r, http.StatusText(http.StatusMethodNotAllowed), http.StatusMethodNotAllowed) |
| 234 |
} |
| 235 |
return |
| 236 |
} |
| 237 |
} |
| 238 |
|
| 239 |
if s.protoErrorHandler != nil { |
| 240 |
_, outboundMarshaler := MarshalerForRequest(s, r) |
| 241 |
sterr := status.Error(codes.Unimplemented, http.StatusText(http.StatusNotImplemented)) |
| 242 |
s.protoErrorHandler(ctx, s, outboundMarshaler, w, r, sterr) |
| 243 |
} else { |
| 244 |
OtherErrorHandler(w, r, http.StatusText(http.StatusNotFound), http.StatusNotFound) |
| 245 |
} |
| 246 |
} |
| 247 |
|
| 248 |
// GetForwardResponseOptions returns the ForwardResponseOptions associated with this ServeMux. |
| 249 |
func (s *ServeMux) GetForwardResponseOptions() []func(context.Context, http.ResponseWriter, proto.Message) error { |
| 250 |
return s.forwardResponseOptions |
| 251 |
} |
| 252 |
|
| 253 |
func isPathLengthFallback(r *http.Request) bool { |
| 254 |
return r.Method == "POST" && r.Header.Get("Content-Type") == "application/x-www-form-urlencoded" |
| 255 |
} |
| 256 |
|
| 257 |
type handler struct { |
| 258 |
pat Pattern |
| 259 |
h HandlerFunc |
| 260 |
} |