package runtimeimport ()// UnescapingMode defines the behavior of ServeMux when unescaping path parameters.typeUnescapingModeintconst (// UnescapingModeLegacy is the default V2 behavior, which escapes the entire // path string before doing any routing.UnescapingModeLegacyUnescapingMode = iota// UnescapingModeAllExceptReserved unescapes all path parameters except RFC 6570 // reserved characters.UnescapingModeAllExceptReserved// UnescapingModeAllExceptSlash unescapes URL path parameters except path // separators, which will be left as "%2F".UnescapingModeAllExceptSlash// UnescapingModeAllCharacters unescapes all URL path parameters.UnescapingModeAllCharacters// UnescapingModeDefault is the default escaping type. // TODO(v3): default this to UnescapingModeAllExceptReserved per grpc-httpjson-transcoding's // reference implementationUnescapingModeDefault = UnescapingModeLegacy)// Percent-encoding is case insensitive (RFC 3986, section 6.2.2.1), so an// escaped path separator has to be recognized in either spelling.var encodedPathSplitter = regexp.MustCompile("(/|%2[fF])")// A HandlerFunc handles a specific pair of path pattern and HTTP method.typeHandlerFuncfunc(w http.ResponseWriter, r *http.Request, pathParams map[string]string)// A Middleware handler wraps another HandlerFunc to do some pre- and/or post-processing of the request. This is used as an alternative to gRPC interceptors when using the direct-to-implementation// registration methods. It is generally recommended to use gRPC client or server interceptors instead// where possible.typeMiddlewarefunc(HandlerFunc) HandlerFunc// ServeMux is a request multiplexer for grpc-gateway.// It matches http requests to patterns and invokes the corresponding handler.typeServeMuxstruct {// handlers maps HTTP method to a list of handlers. handlers map[string][]handler middlewares []Middleware forwardResponseOptions []func(context.Context, http.ResponseWriter, proto.Message) error forwardResponseRewriter ForwardResponseRewriter marshalers marshalerRegistry incomingHeaderMatcher HeaderMatcherFunc outgoingHeaderMatcher HeaderMatcherFunc outgoingTrailerMatcher HeaderMatcherFunc metadataAnnotators []func(context.Context, *http.Request) metadata.MD errorHandler ErrorHandlerFunc streamErrorHandler StreamErrorHandlerFunc routingErrorHandler RoutingErrorHandlerFunc disablePathLengthFallback bool disableHTTPMethodOverride bool unescapingMode UnescapingMode writeContentLength bool disableChunkedEncoding bool strictDeepWildcard bool}// ServeMuxOption is an option that can be given to a ServeMux on construction.typeServeMuxOptionfunc(*ServeMux)// ForwardResponseRewriter is the signature of a function that is capable of rewriting messages// before they are forwarded in a unary, stream, or error response.typeForwardResponseRewriterfunc(ctx context.Context, response proto.Message) (any, error)// WithForwardResponseRewriter returns a ServeMuxOption that allows for implementers to insert logic// that can rewrite the final response before it is forwarded.//// The response rewriter function is called during unary message forwarding, stream message// forwarding and when errors are being forwarded.//// NOTE: Using this option will likely make what is generated by `protoc-gen-openapiv2` incorrect.// Since this option involves making runtime changes to the response shape or type.func ( ForwardResponseRewriter) ServeMuxOption {returnfunc( *ServeMux) { .forwardResponseRewriter = }}// WithForwardResponseOption returns a ServeMuxOption representing the forwardResponseOption.//// forwardResponseOption is an option that will be called on the relevant context.Context,// http.ResponseWriter, and proto.Message before every forwarded response.//// The message may be nil in the case where just a header is being sent.func ( func(context.Context, http.ResponseWriter, proto.Message) error) ServeMuxOption {returnfunc( *ServeMux) { .forwardResponseOptions = append(.forwardResponseOptions, ) }}// WithUnescapingMode sets the escaping type. See the definitions of UnescapingMode// for more information.func ( UnescapingMode) ServeMuxOption {returnfunc( *ServeMux) { .unescapingMode = }}// WithMiddlewares sets server middleware for all handlers. This is useful as an alternative to gRPC// interceptors when using the direct-to-implementation registration methods and cannot rely// on gRPC interceptors. It's recommended to use gRPC interceptors instead if possible.func ( ...Middleware) ServeMuxOption {returnfunc( *ServeMux) { .middlewares = append(.middlewares, ...) }}// WithDisableChunkedEncoding disables the Transfer-Encoding: chunked header// for streaming responses. This is useful for streaming implementations that use// Content-Length, which is mutually exclusive with Transfer-Encoding:chunked.// Note that this option will not automatically add Content-Length headers, so it should be used with caution.func () ServeMuxOption {returnfunc( *ServeMux) { .disableChunkedEncoding = true }}// WithStrictDeepWildcardMatching makes deep wildcards ("**") require at least// one path segment when preceded by another segment. For example,// "/v3/files/{path=**}" will not match "/v3/files". A trailing slash still// provides an empty segment, so "/v3/files/" continues to match.//// This option applies to all patterns registered with the ServeMux, including// generated routes and routes registered with HandlePath.func () ServeMuxOption {returnfunc( *ServeMux) { .strictDeepWildcard = true }}// SetQueryParameterParser sets the query parameter parser, used to populate message from query parameters.// Configuring this will mean the generated OpenAPI output is no longer correct, and it should be// done with careful consideration.func ( QueryParameterParser) ServeMuxOption {returnfunc( *ServeMux) {currentQueryParser = }}// HeaderMatcherFunc checks whether a header key should be forwarded to/from gRPC context.typeHeaderMatcherFuncfunc(string) (string, bool)// DefaultHeaderMatcher is used to pass http request headers to/from gRPC context. This adds permanent HTTP header// keys (as specified by the IANA, e.g: Accept, Cookie, Host) to the gRPC metadata with the grpcgateway- prefix. If you want to know which headers are considered permanent, you can view the isPermanentHTTPHeader function.// Other headers are not added to the gRPC metadata.//// Earlier versions also mapped HTTP headers that start with 'Grpc-Metadata-' to gRPC metadata after removing the// prefix. That let any HTTP client set an arbitrary metadata key, which a backend trusting a key as set by an// interceptor or the gateway itself could not tell apart from the real value. Use LegacyHeaderMatcher, or the// WithLegacyHeaderMatching option, to keep forwarding those headers.func ( string) (string, bool) {if = textproto.CanonicalMIMEHeaderKey(); isPermanentHTTPHeader() {returnMetadataPrefix + , true }return"", false}// LegacyHeaderMatcher is the incoming header matcher earlier releases used by default. In addition to the// permanent HTTP headers DefaultHeaderMatcher maps, HTTP headers that start with 'Grpc-Metadata-' are mapped// to gRPC metadata after removing the prefix 'Grpc-Metadata-'.//// This lets any HTTP client set any metadata key the backend reads, except the ones the gateway reserves for// itself, so only use it when the backend does not trust a metadata key to have been set by the gateway.func ( string) (string, bool) {switch = textproto.CanonicalMIMEHeaderKey(); {caseisPermanentHTTPHeader():returnMetadataPrefix + , truecasestrings.HasPrefix(, MetadataHeaderPrefix): := [len(MetadataHeaderPrefix):]// The grpcgateway- namespace is reserved for permanent HTTP headers the // gateway maps itself, so refuse to forward a Grpc-Metadata- header that // strips into it. Otherwise Grpc-Metadata-grpcgateway-host lets a client // inject a value indistinguishable from the gateway-set grpcgateway-host.ifstrings.HasPrefix(strings.ToLower(), MetadataPrefix) {return"", false }return , true }return"", false}// WithLegacyHeaderMatching returns a ServeMuxOption that restores LegacyHeaderMatcher as the incoming header// matcher, so HTTP headers that start with 'Grpc-Metadata-' are forwarded as gRPC metadata again.func () ServeMuxOption {returnWithIncomingHeaderMatcher(LegacyHeaderMatcher)}func defaultOutgoingHeaderMatcher( string) (string, bool) {returnMetadataHeaderPrefix + , true}func defaultOutgoingTrailerMatcher( string) (string, bool) {returnMetadataTrailerPrefix + , true}// WithIncomingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for incoming request to gateway.//// This matcher will be called with each header in http.Request. If matcher returns true, that header will be// passed to gRPC context. To transform the header before passing to gRPC context, matcher should return the modified header.func ( HeaderMatcherFunc) ServeMuxOption {for , := range .matchedMalformedHeaders() {grpclog.Warningf("The configured forwarding filter would allow %q to be sent to the gRPC server, which will likely cause errors. See https://github.com/grpc/grpc-go/pull/4803#issuecomment-986093310 for more information.", ) }returnfunc( *ServeMux) { .incomingHeaderMatcher = }}// matchedMalformedHeaders returns the malformed headers that would be forwarded to gRPC server.func ( HeaderMatcherFunc) () []string {if == nil {returnnil } := make([]string, 0)for := rangemalformedHTTPHeaders { , := ()if && isMalformedHTTPHeader() { = append(, ) } }return}// WithOutgoingHeaderMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway.//// This matcher will be called with each header in response header metadata. If matcher returns true, that header will be// passed to http response returned from gateway. To transform the header before passing to response,// matcher should return the modified header.func ( HeaderMatcherFunc) ServeMuxOption {returnfunc( *ServeMux) { .outgoingHeaderMatcher = }}// WithOutgoingTrailerMatcher returns a ServeMuxOption representing a headerMatcher for outgoing response from gateway.//// This matcher will be called with each header in response trailer metadata. If matcher returns true, that header will be// passed to http response returned from gateway. To transform the header before passing to response,// matcher should return the modified header.func ( HeaderMatcherFunc) ServeMuxOption {returnfunc( *ServeMux) { .outgoingTrailerMatcher = }}// WithMetadata returns a ServeMuxOption for passing metadata to a gRPC context.//// This can be used by services that need to read from http.Request and modify gRPC context. A common use case// is reading token from cookie and adding it in gRPC context.func ( func(context.Context, *http.Request) metadata.MD) ServeMuxOption {returnfunc( *ServeMux) { .metadataAnnotators = append(.metadataAnnotators, ) }}// WithErrorHandler returns a ServeMuxOption for configuring a custom error handler.//// This can be used to configure a custom error response.func ( ErrorHandlerFunc) ServeMuxOption {returnfunc( *ServeMux) { .errorHandler = }}// WithStreamErrorHandler returns a ServeMuxOption that will use the given custom stream// error handler, which allows for customizing the error trailer for server-streaming// calls.//// For stream errors that occur before any response has been written, the mux's// ErrorHandler will be invoked. However, once data has been written, the errors must// be handled differently: they must be included in the response body. The response body's// final message will include the error details returned by the stream error handler.func ( StreamErrorHandlerFunc) ServeMuxOption {returnfunc( *ServeMux) { .streamErrorHandler = }}// WithRoutingErrorHandler returns a ServeMuxOption for configuring a custom error handler to handle http routing errors.//// Method called for errors which can happen before gRPC route selected or executed.// The following error codes: StatusMethodNotAllowed StatusNotFound StatusBadRequestfunc ( RoutingErrorHandlerFunc) ServeMuxOption {returnfunc( *ServeMux) { .routingErrorHandler = }}// WithDisablePathLengthFallback returns a ServeMuxOption for disable path length fallback.func () ServeMuxOption {returnfunc( *ServeMux) { .disablePathLengthFallback = true }}// WithDisableHTTPMethodOverride returns a ServeMuxOption that disables the// X-HTTP-Method-Override header handling.//// When this option is used, the mux will no longer allow POST requests with// the X-HTTP-Method-Override header to override the HTTP method. The path// length fallback (POST with application/x-www-form-urlencoded falling back// to a matching GET handler) is not affected by this option.func () ServeMuxOption {returnfunc( *ServeMux) { .disableHTTPMethodOverride = true }}// WithWriteContentLength returns a ServeMuxOption to enable writing content length on non-streaming responsesfunc () ServeMuxOption {returnfunc( *ServeMux) { .writeContentLength = true }}// WithHealthEndpointAt returns a ServeMuxOption that will add an endpoint to the created ServeMux at the path specified by endpointPath.// When called the handler will forward the request to the upstream grpc service health check (defined in the// gRPC Health Checking Protocol).//// See here https://grpc-ecosystem.github.io/grpc-gateway/docs/operations/health_check/ for more information on how// to setup the protocol in the grpc server.//// If you define a service as query parameter, this will also be forwarded as service in the HealthCheckRequest.func ( grpc_health_v1.HealthClient, string) ServeMuxOption {returnfunc( *ServeMux) {// error can be ignored since pattern is definitely valid _ = .HandlePath(http.MethodGet, , func( http.ResponseWriter, *http.Request, map[string]string, ) { , := MarshalerForRequest(, ) , := AnnotateContext(.Context(), , , grpc_health_v1.Health_Check_FullMethodName, WithHTTPPathPattern())if != nil { .errorHandler(.Context(), , , , , )return }varServerMetadata , := .Check(, &grpc_health_v1.HealthCheckRequest{Service: .URL.Query().Get("service"), }, grpc.Header(&.HeaderMD), grpc.Trailer(&.TrailerMD)) = NewServerMetadataContext(, )if != nil { .errorHandler(, , , , , )return } .Header().Set("Content-Type", "application/json")if .GetStatus() != grpc_health_v1.HealthCheckResponse_SERVING {switch .GetStatus() {casegrpc_health_v1.HealthCheckResponse_NOT_SERVING, grpc_health_v1.HealthCheckResponse_UNKNOWN: = status.Error(codes.Unavailable, .String())casegrpc_health_v1.HealthCheckResponse_SERVICE_UNKNOWN: = status.Error(codes.NotFound, .String()) } .errorHandler(, , , , , )return } _ = .NewEncoder().Encode() }) }}// WithHealthzEndpoint returns a ServeMuxOption that will add a /healthz endpoint to the created ServeMux.//// See WithHealthEndpointAt for the general implementation.func ( grpc_health_v1.HealthClient) ServeMuxOption {returnWithHealthEndpointAt(, "/healthz")}// NewServeMux returns a new ServeMux whose internal mapping is empty.func ( ...ServeMuxOption) *ServeMux { := &ServeMux{handlers: make(map[string][]handler),forwardResponseOptions: make([]func(context.Context, http.ResponseWriter, proto.Message) error, 0),forwardResponseRewriter: func( context.Context, proto.Message) (any, error) { return , nil },marshalers: makeMarshalerMIMERegistry(),errorHandler: DefaultHTTPErrorHandler,streamErrorHandler: DefaultStreamErrorHandler,routingErrorHandler: DefaultRoutingErrorHandler,unescapingMode: UnescapingModeDefault, }for , := range { () }if .incomingHeaderMatcher == nil { .incomingHeaderMatcher = DefaultHeaderMatcher }if .outgoingHeaderMatcher == nil { .outgoingHeaderMatcher = defaultOutgoingHeaderMatcher }if .outgoingTrailerMatcher == nil { .outgoingTrailerMatcher = defaultOutgoingTrailerMatcher }// Options such as WithHealthEndpointAt register handlers while the options // are still being applied, so they were wrapped with only the middlewares // configured before them. Rewrap them now that all middlewares are known.iflen(.middlewares) > 0 { := chainMiddlewares(.middlewares)for , := range .handlers {for := range { [].h = ([].raw) } } }return}// Handle associates "h" to the pair of HTTP method and path pattern.func ( *ServeMux) ( string, Pattern, HandlerFunc) { := iflen(.middlewares) > 0 { = chainMiddlewares(.middlewares)() } .handlers[] = append([]handler{{pat: , h: , raw: }}, .handlers[]...)}// HandlePath allows users to configure custom path handlers.// refer: https://grpc-ecosystem.github.io/grpc-gateway/docs/operations/inject_router/func ( *ServeMux) ( string, string, HandlerFunc) error { , := httprule.Parse()if != nil {returnfmt.Errorf("parsing path pattern: %w", ) } := .Compile() , := NewPattern(.Version, .OpCodes, .Pool, .Verb)if != nil {returnfmt.Errorf("creating new pattern: %w", ) } .Handle(, , )returnnil}// ServeHTTP dispatches the request to the first handler whose pattern matches to r.Method and r.URL.Path.func ( *ServeMux) ( http.ResponseWriter, *http.Request) { := .Context() := .URL.Pathif !strings.HasPrefix(, "/") { , := MarshalerForRequest(, ) .routingErrorHandler(, , , , , http.StatusBadRequest)return }// TODO(v3): remove UnescapingModeLegacy := .unescapingModeif != UnescapingModeLegacy {if .URL.RawPath != "" { = .URL.RawPath } else {// net/url only sets RawPath when the request path is not in its // default encoding. Without it, Path is all there is and it has // already been unescaped once, so unescaping it again while matching // would decode a sequence like %252F twice. = UnescapingModeLegacy } }// "X-Http-Method-Override" is the canonical spelling; Header.Get allocates a // canonicalised copy of any other, and this lookup happens on every request.if := .Header.Get("X-Http-Method-Override"); != "" && !.disableHTTPMethodOverride && .isPathLengthFallback() {if := .ParseForm(); != nil { , := MarshalerForRequest(, ) := status.Error(codes.InvalidArgument, .Error()) .errorHandler(, , , , , )return } .Method = strings.ToUpper() }var []string// since in UnescapeModeLegacy, the URL will already have been fully unescaped, if we also split on "%2F" // in this escaping mode we would be double unescaping but in UnescapingModeAllCharacters, we still do as the // path is the RawPath (i.e. unescaped). That does mean that the behavior of this function will change its default // behavior when the UnescapingModeDefault gets changed from UnescapingModeLegacy to UnescapingModeAllExceptReservedif == UnescapingModeAllCharacters { = encodedPathSplitter.Split([1:], -1) } else { = strings.Split([1:], "/") } := [len()-1]for , := range .handlers[.Method] {// If the pattern has a verb, explicitly look for a suffix in the last // component that matches a colon plus the verb. This allows us to // handle some cases that otherwise can't be correctly handled by the // former LastIndex case, such as when the verb literal itself contains // a colon. This should work for all cases that have run through the // parser because we know what verb we're looking for, however, there // are still some cases that the parser itself cannot disambiguate. See // the comment there if interested.varstring := .pat.Verb() := -1if != "" && strings.HasSuffix(, ":"+) { = len() - len() - 1 }if == 0 {// The last component is the bare verb with nothing before it, // which this pattern cannot match. Other patterns still might, so // move on rather than ending the search with a 404.continue }// Only copy the components when the verb has to be split off the last // one. MatchAndEscape never mutates its input, so sharing the slice // across handlers is safe, and copying it per handler otherwise costs // len(pathComponents) allocations for every registered pattern. := if > 0 { = make([]string, len())copy(, ) [len()-1], = [:], [+1:] } , := .pat.matchAndEscape(, , , .strictDeepWildcard)if != nil {// ErrNotMatch is returned once for every registered pattern the request does not // match, so it is by far the most common error reaching this branch. Checking it // first keeps errors.As off that path: its target parameter is an any, so &mse is // boxed onto the heap on every call -- one allocation per route a request did not // match, which grows with the number of registered routes.iferrors.Is(, ErrNotMatch) {continue }varMalformedSequenceErrorif := errors.As(, &); { , := MarshalerForRequest(, ) .errorHandler(, , , , , &HTTPStatusError{HTTPStatus: http.StatusBadRequest,Err: , })return }continue } .handleHandler(, , , )return }// if no handler has found for the request, lookup for other methods // to handle POST -> GET fallback if the request is subject to path // length fallback. // Note we are not eagerly checking the request here as we want to return the // right HTTP status code, and we need to process the fallback candidates in // order to do that. // GET is tried first when the request is subject to path length fallback: // map iteration order is random, and a match for another method would // otherwise return 405 before the GET handler is reached. := make([]string, 0, len(.handlers))if .isPathLengthFallback() { = append(, http.MethodGet) }for := range .handlers {if == http.MethodGet && .isPathLengthFallback() {continue } = append(, ) }for , := range {if == .Method {continue }for , := range .handlers[] {varstring := .pat.Verb() := -1if != "" && strings.HasSuffix(, ":"+) { = len() - len() - 1 } := if > 0 { = make([]string, len())copy(, ) [len()-1], = [:], [+1:] } , := .pat.matchAndEscape(, , , .strictDeepWildcard)if != nil {varMalformedSequenceErrorif := errors.As(, &); { , := MarshalerForRequest(, ) .errorHandler(, , , , , &HTTPStatusError{HTTPStatus: http.StatusBadRequest,Err: , })return }continue }// X-HTTP-Method-Override is optional. Always allow fallback to POST. // Also, only consider POST -> GET fallbacks, and avoid falling back to // potentially dangerous operations like DELETE.if .isPathLengthFallback() && == http.MethodGet {if := .ParseForm(); != nil { , := MarshalerForRequest(, ) := status.Error(codes.InvalidArgument, .Error()) .errorHandler(, , , , , )return } .handleHandler(, , , )return } , := MarshalerForRequest(, ) .routingErrorHandler(, , , , , http.StatusMethodNotAllowed)return } } , := MarshalerForRequest(, ) .routingErrorHandler(, , , , , http.StatusNotFound)}// GetForwardResponseOptions returns the ForwardResponseOptions associated with this ServeMux.func ( *ServeMux) () []func(context.Context, http.ResponseWriter, proto.Message) error {return .forwardResponseOptions}func ( *ServeMux) ( *http.Request) bool {if .disablePathLengthFallback || .Method != http.MethodPost {returnfalse }// Like net/http's ParseForm, ignore parameters such as charset. , , := mime.ParseMediaType(.Header.Get("Content-Type"))return == nil && == "application/x-www-form-urlencoded"}type handler struct { pat Pattern h HandlerFunc// raw is h before middlewares were applied. raw HandlerFunc}func ( *ServeMux) ( handler, http.ResponseWriter, *http.Request, map[string]string) { .h(, .WithContext(withHTTPPattern(.Context(), .pat)), )}func chainMiddlewares( []Middleware) Middleware {returnfunc( HandlerFunc) HandlerFunc {for := len(); > 0; -- { = [-1]() }return }}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.