package runtimeimport ()// MetadataHeaderPrefix is the http prefix that represents custom metadata// parameters to or from a gRPC call.constMetadataHeaderPrefix = "Grpc-Metadata-"// MetadataPrefix is prepended to permanent HTTP header keys (as specified// by the IANA) when added to the gRPC context.constMetadataPrefix = "grpcgateway-"// MetadataTrailerPrefix is prepended to gRPC metadata as it is converted to// HTTP headers in a response handled by grpc-gatewayconstMetadataTrailerPrefix = "Grpc-Trailer-"const metadataGrpcTimeout = "Grpc-Timeout"const metadataHeaderBinarySuffix = "-Bin"const xForwardedFor = "X-Forwarded-For"const xForwardedHost = "X-Forwarded-Host"// gRPC metadata keys are lower-case, so these two are appended to the pairs under their// lower-case spelling. Writing it out as a constant keeps strings.ToLower off the per-request// path, where it allocated a new string for a compile-time constant on every call, and lets// metadata.Pairs skip its own lower-casing for these keys as well.const xForwardedForKey = "x-forwarded-for"const xForwardedHostKey = "x-forwarded-host"// DefaultContextTimeout is used for gRPC call context.WithTimeout whenever a Grpc-Timeout inbound// header isn't present. If the value is 0 the sent `context` will not have a timeout.varDefaultContextTimeout = 0 * time.Second// malformedHTTPHeaders lists the headers that the gRPC server may reject outright as malformed.// See https://github.com/grpc/grpc-go/pull/4803#issuecomment-986093310 for more context.var malformedHTTPHeaders = map[string]struct{}{"connection": {},}type ( rpcMethodKey struct{} httpPathPatternKey struct{} httpPatternKey struct{}AnnotateContextOptionfunc(ctx context.Context) context.Context)func ( string) AnnotateContextOption {returnfunc( context.Context) context.Context {returnwithHTTPPathPattern(, ) }}func decodeBinHeader( string) ([]byte, error) {iflen()%4 == 0 {// Input was padded, or padding was not necessary.returnbase64.StdEncoding.DecodeString() }returnbase64.RawStdEncoding.DecodeString()}/*AnnotateContext adds context information such as metadata from the request.At a minimum, the RemoteAddr is included in the fashion of "X-Forwarded-For",except that the forwarded destination is not another HTTP service but rathera gRPC service.*/func ( context.Context, *ServeMux, *http.Request, string, ...AnnotateContextOption) (context.Context, error) { , , := annotateContext(, , , , ...)if != nil {returnnil, }if == nil {return , nil }returnmetadata.NewOutgoingContext(, ), nil}// AnnotateIncomingContext adds context information such as metadata from the request.// Attach metadata as incoming context.func ( context.Context, *ServeMux, *http.Request, string, ...AnnotateContextOption) (context.Context, error) { , , := annotateContext(, , , , ...)if != nil {returnnil, }if == nil {return , nil }returnmetadata.NewIncomingContext(, ), nil}func isValidGRPCMetadataKey( string) bool {// Must be a valid gRPC "Header-Name" as defined here: // https://github.com/grpc/grpc/blob/4b05dc88b724214d0c725c8e7442cbc7a61b1374/doc/PROTOCOL-HTTP2.md // This means 0-9 a-z _ - . // Only lowercase letters are valid in the wire protocol, but the client library will normalize // uppercase ASCII to lowercase, so uppercase ASCII is also acceptable. // An empty key is not a valid header name, and gRPC fails the call with one.if == "" {returnfalse } := []byte() // gRPC validates strings on the byte level, not Unicode.for , := range { := >= 'a' && <= 'z' := >= 'A' && <= 'Z' := >= '0' && <= '9' := == '.' || == '-' || == '_'if ! && ! && ! && ! {returnfalse } }returntrue}func isValidGRPCMetadataTextValue( string) bool {// Must be a valid gRPC "ASCII-Value" as defined here: // https://github.com/grpc/grpc/blob/4b05dc88b724214d0c725c8e7442cbc7a61b1374/doc/PROTOCOL-HTTP2.md // This means printable ASCII (including/plus spaces); 0x20 to 0x7E inclusive. := []byte() // gRPC validates strings on the byte level, not Unicode.for , := range {if < 0x20 || > 0x7E {returnfalse } }returntrue}func annotateContext( context.Context, *ServeMux, *http.Request, string, ...AnnotateContextOption) (context.Context, metadata.MD, error) { = withRPCMethod(, )for , := range { = () } := DefaultContextTimeoutif := .Header.Get(metadataGrpcTimeout); != "" {varerror , = timeoutDecode()if != nil {returnnil, nil, status.Errorf(codes.InvalidArgument, "invalid grpc-timeout: %s", ) } }// Each forwarded header contributes a key and a value, and the two X-Forwarded-* pairs the // gateway derives below add two more. Sizing for that up front replaces the handful of // reallocations an empty slice goes through while it doubles. := make([]string, 0, 2*(len(.Header)+2))// For backwards-compatibility, pass through 'authorization' header with no prefix. // It is added before the header loop so that it is always the first // "authorization" value: the loop iterates a map, so a header the matcher // forwards under the same key (Grpc-Metadata-Authorization with the default // matcher) would otherwise land ahead of it in random order, and a backend // reading the first value would get the client-forwarded one.for , := range .Header.Values("Authorization") {ifisValidGRPCMetadataTextValue() { = append(, "authorization", ) } }for , := range .Header { = textproto.CanonicalMIMEHeaderKey()switch {casexForwardedFor, xForwardedHost:// Handled separately belowcontinue }for , := range {if , := .incomingHeaderMatcher(); {// The gateway derives x-forwarded-host and x-forwarded-for below from // the trusted request (Host / X-Forwarded-* / RemoteAddr), and backends // rely on those metadata keys for client host/IP decisions. Refuse a // forwarded header that the matcher strips into one of them (e.g. // Grpc-Metadata-X-Forwarded-For) so a client cannot slip a spoofed value // in ahead of the gateway-set one.ifstrings.EqualFold(, xForwardedFor) || strings.EqualFold(, xForwardedHost) {grpclog.Errorf("HTTP header %q maps to gateway-reserved metadata key %q; skipping", , )continue }if !isValidGRPCMetadataKey() {grpclog.Errorf("HTTP header name %q is not valid as gRPC metadata key; skipping", )continue }// Handles "-bin" metadata in grpc, since grpc will do another base64 // encode before sending to server, we need to decode it first.ifstrings.HasSuffix(, metadataHeaderBinarySuffix) { , := decodeBinHeader()if != nil {returnnil, nil, status.Errorf(codes.InvalidArgument, "invalid binary header %s: %s", , ) } = string() } elseif !isValidGRPCMetadataTextValue() {grpclog.Errorf("Value of HTTP header %q contains non-ASCII value (not valid as gRPC metadata): skipping", )continue } = append(, , ) } } }if := .Header.Get(xForwardedHost); != "" && isValidGRPCMetadataTextValue() { = append(, xForwardedHostKey, ) } elseif .Host != "" && isValidGRPCMetadataTextValue(.Host) { = append(, xForwardedHostKey, .Host) }// Validate each X-Forwarded-For value on its own, so that an invalid // client-supplied value is dropped without also dropping the remote // address the gateway appends.var []stringfor , := range .Header.Values(xForwardedFor) {ifisValidGRPCMetadataTextValue() { = append(, ) } }if := .RemoteAddr; != "" {if , , := net.SplitHostPort(); == nil && isValidGRPCMetadataTextValue() { = append(, ) } }iflen() > 0 { = append(, xForwardedForKey, strings.Join(, ", ")) }if != 0 { , _ = context.WithTimeout(, ) } := metadata.Pairs(...)varmetadata.MDfor , := range .metadataAnnotators { = metadata.Join(, (, )) }// Annotators are the gateway's own code, so their values replace whatever // the request headers put under the same key. Joining them after the // header values would let a client send Grpc-Metadata-<key> and have its // value read first by a backend that trusts the annotator. // // With no annotators registered -- the default -- there is nothing to merge, and // metadata.Join would rebuild the whole map for nothing: it starts from an empty MD and // appends every key's values into a fresh slice, so the result is an identical copy of md // bought with one allocation per key.iflen() > 0 {for := range {delete(, strings.ToLower()) } = metadata.Join(, ) }iflen() == 0 {return , nil, nil }return , , nil}// ServerMetadata consists of metadata sent from gRPC server.typeServerMetadatastruct { HeaderMD metadata.MD TrailerMD metadata.MD}type serverMetadataKey struct{}// NewServerMetadataContext creates a new context with ServerMetadatafunc ( context.Context, ServerMetadata) context.Context {if == nil { = context.Background() }returncontext.WithValue(, serverMetadataKey{}, )}// ServerMetadataFromContext returns the ServerMetadata in ctxfunc ( context.Context) ( ServerMetadata, bool) {if == nil {return , false } , = .Value(serverMetadataKey{}).(ServerMetadata)return}// ServerTransportStream implements grpc.ServerTransportStream.// It should only be used by the generated files to support grpc.SendHeader// outside of gRPC server use.typeServerTransportStreamstruct { mu sync.Mutex header metadata.MD trailer metadata.MD}// Method returns the method for the stream.func ( *ServerTransportStream) () string {return""}// Header returns the header metadata of the stream.func ( *ServerTransportStream) () metadata.MD { .mu.Lock()defer .mu.Unlock()return .header.Copy()}// SetHeader sets the header metadata.func ( *ServerTransportStream) ( metadata.MD) error {if .Len() == 0 {returnnil } .mu.Lock() .header = metadata.Join(.header, ) .mu.Unlock()returnnil}// SendHeader sets the header metadata.func ( *ServerTransportStream) ( metadata.MD) error {return .SetHeader()}// Trailer returns the cached trailer metadata.func ( *ServerTransportStream) () metadata.MD { .mu.Lock()defer .mu.Unlock()return .trailer.Copy()}// SetTrailer sets the trailer metadata.func ( *ServerTransportStream) ( metadata.MD) error {if .Len() == 0 {returnnil } .mu.Lock() .trailer = metadata.Join(.trailer, ) .mu.Unlock()returnnil}func timeoutDecode( string) (time.Duration, error) { := len()if < 2 {return0, fmt.Errorf("timeout string is too short: %q", ) } , := timeoutUnitToDuration([-1])if ! {return0, fmt.Errorf("timeout unit is not recognized: %q", ) } , := strconv.ParseUint([:-1], 10, 64)if != nil {return0, }// Guard against overflowing time.Duration, which is an int64 nanosecond // count: without this a large value wraps to a bogus (often negative) // deadline instead of the long timeout the client asked for.if > uint64(math.MaxInt64)/uint64() {returntime.Duration(math.MaxInt64), nil }return * time.Duration(), nil}func timeoutUnitToDuration( uint8) ( time.Duration, bool) {switch {case'H':returntime.Hour, truecase'M':returntime.Minute, truecase'S':returntime.Second, truecase'm':returntime.Millisecond, truecase'u':returntime.Microsecond, truecase'n':returntime.Nanosecond, truedefault:return }}// isPermanentHTTPHeader checks whether hdr belongs to the list of// permanent request headers maintained by IANA.// http://www.iana.org/assignments/message-headers/message-headers.xmlfunc isPermanentHTTPHeader( string) bool {switch {case"Accept","Accept-Charset","Accept-Language","Accept-Ranges","Authorization","Cache-Control","Content-Type","Cookie","Date","Expect","From","Host","If-Match","If-Modified-Since","If-None-Match","If-Schedule-Tag-Match","If-Unmodified-Since","Max-Forwards","Origin","Pragma","Referer","User-Agent","Via","Warning":returntrue }returnfalse}// isMalformedHTTPHeader checks whether header belongs to the list of// "malformed headers" and would be rejected by the gRPC server.func isMalformedHTTPHeader( string) bool { , := malformedHTTPHeaders[strings.ToLower()]return}// RPCMethod returns the method string for the server context. The returned// string is in the format of "/package.service/method".func ( context.Context) (string, bool) { := .Value(rpcMethodKey{})if == nil {return"", false } , := .(string)if ! {return"", false }return , true}func withRPCMethod( context.Context, string) context.Context {returncontext.WithValue(, rpcMethodKey{}, )}// HTTPPathPattern returns the HTTP path pattern string relating to the HTTP handler, if one exists.// The format of the returned string is defined by the google.api.http path template type.func ( context.Context) (string, bool) { := .Value(httpPathPatternKey{})if == nil {return"", false } , := .(string)if ! {return"", false }return , true}func withHTTPPathPattern( context.Context, string) context.Context {returncontext.WithValue(, httpPathPatternKey{}, )}// HTTPPattern returns the HTTP path pattern struct relating to the HTTP handler, if one exists.func ( context.Context) (Pattern, bool) { , := .Value(httpPatternKey{}).(Pattern)return , }func withHTTPPattern( context.Context, Pattern) context.Context {returncontext.WithValue(, httpPatternKey{}, )}
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.