package runtimeimport ()var (// ErrNotMatch indicates that the given HTTP request path does not match to the pattern.ErrNotMatch = errors.New("not match to the path pattern")// ErrInvalidPattern indicates that the given definition of Pattern is not valid.ErrInvalidPattern = errors.New("invalid pattern"))typeMalformedSequenceErrorstringfunc ( MalformedSequenceError) () string {return"malformed path escape " + strconv.Quote(string())}type op struct { code utilities.OpCode operand int// multisegment is set on an OpPush that is one segment of a variable // spanning several segments, such as the "*" in {name=shelves/*}. multisegment bool}// Pattern is a template pattern of http request paths defined in// https://github.com/googleapis/googleapis/blob/master/google/api/http.prototypePatternstruct {// ops is a list of operations ops []op// pool is a constant pool indexed by the operands or vars. pool []string// vars is a list of variables names to be bound by this pattern vars []string// stacksize is the max depth of the stack stacksize int// tailLen is the length of the fixed-size segments after a deep wildcard tailLen int// verb is the VERB part of the path pattern. It is empty if the pattern does not have VERB part. verb string// strictDeepWildcard makes a deep wildcard ("**") preceded by a segment require at least one // remaining path component. strictDeepWildcard bool}// PatternOpt configures optional behavior of a Pattern.typePatternOptfunc(*Pattern)// WithStrictDeepWildcard makes a deep wildcard ("**") that is preceded by another// segment refuse to match zero path segments. For example, "/v3/files/{path=**}"// will not match "/v3/files". A bare "**" with nothing preceding it still matches// zero segments. See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.func () PatternOpt {returnfunc( *Pattern) { .strictDeepWildcard = true }}// NewPattern returns a new Pattern from the given definition values.// "ops" is a sequence of op codes. "pool" is a constant pool.// "verb" is the verb part of the pattern. It is empty if the pattern does not have the part.// "version" must be 1 for now.// It returns an error if the given definition is invalid.func ( int, []int, []string, string) (Pattern, error) {returnNewPatternWithOptions(, , , )}// NewPatternWithOptions is like NewPattern but additionally accepts options that modify// the matching behavior of the returned Pattern, e.g. WithStrictDeepWildcard.func ( int, []int, []string, string, ...PatternOpt) (Pattern, error) {if != 1 {grpclog.Errorf("unsupported version: %d", )returnPattern{}, ErrInvalidPattern } := len()if %2 != 0 {grpclog.Errorf("odd number of ops codes: %d", )returnPattern{}, ErrInvalidPattern }var ( []op , intintbool []string )for := 0; < ; += 2 { := op{code: utilities.OpCode([]), operand: [+1]}switch .code {caseutilities.OpNop:continuecaseutilities.OpPush:if { ++ } ++caseutilities.OpPushM:if {grpclog.Error("pushM appears twice")returnPattern{}, ErrInvalidPattern } = true ++caseutilities.OpLitPush:if .operand < 0 || len() <= .operand {grpclog.Errorf("negative literal index: %d", .operand)returnPattern{}, ErrInvalidPattern }if { ++ } ++caseutilities.OpConcatN:if .operand <= 0 {grpclog.Errorf("negative concat size: %d", .operand)returnPattern{}, ErrInvalidPattern } -= .operandif < 0 {grpclog.Error("stack underflow")returnPattern{}, ErrInvalidPattern } ++// The segments of a variable are the ops pushed right before its // OpConcatN, so these are the ones of a multi-segment variable.if .operand > 1 {for := len() - .operand; < len(); ++ {if [].code == utilities.OpPush { [].multisegment = true } } }caseutilities.OpCapture:if .operand < 0 || len() <= .operand {grpclog.Errorf("variable name index out of bound: %d", .operand)returnPattern{}, ErrInvalidPattern } := [.operand] .operand = len() = append(, ) --if < 0 {grpclog.Error("stack underflow")returnPattern{}, ErrInvalidPattern }default:grpclog.Errorf("invalid opcode: %d", .code)returnPattern{}, ErrInvalidPattern }if < { = } = append(, ) } := Pattern{ops: ,pool: ,vars: ,stacksize: ,tailLen: ,verb: , }for , := range { (&) }return , nil}// MustPattern is a helper function which makes it easier to call NewPattern in variable initialization.func ( Pattern, error) Pattern {if != nil {grpclog.Fatalf("Pattern initialization failed: %v", ) }return}// MatchAndEscape examines components to determine if they match to a Pattern.// MatchAndEscape will return an error if no Patterns matched or if a pattern// matched but contained malformed escape sequences. If successful, the function// returns a mapping from field paths to their captured values.func ( Pattern) ( []string, string, UnescapingMode) (map[string]string, error) {return .matchAndEscape(, , , false)}func ( Pattern) ( []string, string, UnescapingMode, bool) (map[string]string, error) {if .verb != {if .verb != "" {returnnil, ErrNotMatch }iflen() == 0 { = []string{":" + } } else { = append([]string{}, ...) [len()-1] += ":" + } }varint// Scratch space for the match. Neither backing array escapes -- only the individual // strings they hold are copied into the returned bindings -- so fixed-size arrays keep // both off the heap for the patterns generated code registers, where the stack size and // the variable count are single digits. // // This matters beyond one allocation each: ServeHTTP calls matchAndEscape once per // registered pattern until one matches, and both allocations happened before the // non-match return below, so a request paid for them once for every route it did not // match. With a few dozen routes registered that was the largest single source of // allocations in routing.var , [8]string := [:0]if .stacksize > len() { = make([]string, 0, .stacksize) }var []stringif := len(.vars); <= len() { = [:] } else { = make([]string, ) } := len()for , := range .ops {varerrorswitch .code {caseutilities.OpNop:continuecaseutilities.OpPush, utilities.OpLitPush:if >= {returnnil, ErrNotMatch } := []if .code == utilities.OpLitPush {if := .pool[.operand]; != {returnnil, ErrNotMatch } } elseif .code == utilities.OpPush {// google.api.http decodes a variable spanning several segments // "except %2F and %2f", so a "*" in it can't add a path separator // to the bound value. Other escapes are decoded as for {var}. := if .multisegment && == UnescapingModeAllExceptReserved { = UnescapingModeAllExceptSlash }if , = unescape(, , .multisegment); != nil {returnnil, } } = append(, ) ++caseutilities.OpPushM: := len()if < +.tailLen {returnnil, ErrNotMatch } -= .tailLenif (.strictDeepWildcard || ) && > 0 && == {// A deep wildcard ("**") is allowed to match zero path segments when it is // the first thing being matched in the pattern (pos == 0). But once a literal // or variable segment has already consumed a component, "**" needs the request // path to continue past that segment — it cannot succeed with nothing left to // consume at all (though an empty trailing segment, e.g. from a trailing slash, // still counts as a real component and is fine). // See https://github.com/grpc-ecosystem/grpc-gateway/issues/5771.returnnil, ErrNotMatch } := strings.Join([:], "/")if , = unescape(, , true); != nil {returnnil, } = append(, ) = caseutilities.OpConcatN: := .operand := len() - = append([:], strings.Join([:], "/"))caseutilities.OpCapture: := len() - 1 [.operand] = [] = [:] } }if < {returnnil, ErrNotMatch } := make(map[string]string)for , := range { [.vars[]] = }return , nil}// MatchAndEscape examines components to determine if they match to a Pattern.// It will never perform per-component unescaping (see: UnescapingModeLegacy).// MatchAndEscape will return an error if no Patterns matched. If successful,// the function returns a mapping from field paths to their captured values.//// Deprecated: Use MatchAndEscape.func ( Pattern) ( []string, string) (map[string]string, error) {return .MatchAndEscape(, , UnescapingModeDefault)}// Verb returns the verb part of the Pattern.func ( Pattern) () string { return .verb }func ( Pattern) () string {var []stringfor , := range .ops {switch .code {caseutilities.OpNop:continuecaseutilities.OpPush: = append(, "*")caseutilities.OpLitPush: = append(, .pool[.operand])caseutilities.OpPushM: = append(, "**")caseutilities.OpConcatN: := .operand := len() - = append([:], strings.Join([:], "/"))caseutilities.OpCapture: := len() - 1 [] = fmt.Sprintf("{%s=%s}", .vars[.operand], []) } } := strings.Join(, "/")if .verb != "" {returnfmt.Sprintf("/%s:%s", , .verb) }return"/" + }/* * The following code is adopted and modified from Go's standard library * and carries the attached license. * * Copyright 2009 The Go Authors. All rights reserved. * Use of this source code is governed by a BSD-style * license that can be found in the LICENSE file. */// ishex returns whether or not the given byte is a valid hex characterfunc ishex( byte) bool {switch {case'0' <= && <= '9':returntruecase'a' <= && <= 'f':returntruecase'A' <= && <= 'F':returntrue }returnfalse}func isRFC6570Reserved( byte) bool {switch {case'!', '#', '$', '&', '\'', '(', ')', '*','+', ',', '/', ':', ';', '=', '?', '@', '[', ']':returntruedefault:returnfalse }}// unhex converts a hex point to the bit representationfunc unhex( byte) byte {switch {case'0' <= && <= '9':return - '0'case'a' <= && <= 'f':return - 'a' + 10case'A' <= && <= 'F':return - 'A' + 10 }return0}// shouldUnescapeWithMode returns true if the character is escapable with the// given modefunc shouldUnescapeWithMode( byte, UnescapingMode) bool {switch {caseUnescapingModeAllExceptReserved:ifisRFC6570Reserved() {returnfalse }caseUnescapingModeAllExceptSlash:if == '/' {returnfalse }caseUnescapingModeAllCharacters:returntrue }returntrue}// unescape unescapes a path string using the provided modefunc unescape( string, UnescapingMode, bool) (string, error) {// TODO(v3): remove UnescapingModeLegacyif == UnescapingModeLegacy {return , nil }if ! { = UnescapingModeAllCharacters }// Count %, check that they're well-formed. := 0for := 0; < len(); {if [] == '%' { ++if +2 >= len() || !ishex([+1]) || !ishex([+2]) { = [:]iflen() > 3 { = [:3] }return"", MalformedSequenceError() } += 3 } else { ++ } }if == 0 {return , nil }varstrings.Builder .Grow(len())for := 0; < len(); ++ {switch [] {case'%': := unhex([+1])<<4 | unhex([+2])ifshouldUnescapeWithMode(, ) { .WriteByte() += 2continue }fallthroughdefault: .WriteByte([]) } }return .String(), nil}
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.