...

Source file src/github.com/emicklei/go-restful/v3/path_processor.go

Documentation: github.com/emicklei/go-restful/v3

     1  package restful
     2  
     3  import (
     4  	"bytes"
     5  	"strings"
     6  )
     7  
     8  // Copyright 2018 Ernest Micklei. All rights reserved.
     9  // Use of this source code is governed by a license
    10  // that can be found in the LICENSE file.
    11  
    12  // PathProcessor is extra behaviour that a Router can provide to extract path parameters from the path.
    13  // If a Router does not implement this interface then the default behaviour will be used.
    14  type PathProcessor interface {
    15  	// ExtractParameters gets the path parameters defined in the route and webService from the urlPath
    16  	ExtractParameters(route *Route, webService *WebService, urlPath string) map[string]string
    17  }
    18  
    19  type defaultPathProcessor struct{}
    20  
    21  // Extract the parameters from the request url path
    22  func (d defaultPathProcessor) ExtractParameters(r *Route, _ *WebService, urlPath string) map[string]string {
    23  	urlParts := tokenizePath(urlPath)
    24  	pathParameters := map[string]string{}
    25  	for i, key := range r.pathParts {
    26  		var value string
    27  		if i >= len(urlParts) {
    28  			value = ""
    29  		} else {
    30  			value = urlParts[i]
    31  		}
    32  		if r.hasCustomVerb && hasCustomVerb(key) {
    33  			key = removeCustomVerb(key)
    34  			value = removeCustomVerb(value)
    35  		}
    36  
    37  		if strings.Index(key, "{") > -1 { // path-parameter
    38  			if colon := strings.Index(key, ":"); colon != -1 {
    39  				// extract by regex
    40  				regPart := key[colon+1 : len(key)-1]
    41  				keyPart := key[1:colon]
    42  				if regPart == "*" {
    43  					pathParameters[keyPart] = untokenizePath(i, urlParts)
    44  					break
    45  				} else {
    46  					pathParameters[keyPart] = value
    47  				}
    48  			} else {
    49  				// without enclosing {}
    50  				startIndex := strings.Index(key, "{")
    51  				endKeyIndex := strings.Index(key, "}")
    52  
    53  				suffixLength := len(key) - endKeyIndex - 1
    54  				endValueIndex := len(value) - suffixLength
    55  
    56  				pathParameters[key[startIndex+1:endKeyIndex]] = value[startIndex:endValueIndex]
    57  			}
    58  		}
    59  	}
    60  	return pathParameters
    61  }
    62  
    63  // Untokenize back into an URL path using the slash separator
    64  func untokenizePath(offset int, parts []string) string {
    65  	var buffer bytes.Buffer
    66  	for p := offset; p < len(parts); p++ {
    67  		buffer.WriteString(parts[p])
    68  		// do not end
    69  		if p < len(parts)-1 {
    70  			buffer.WriteString("/")
    71  		}
    72  	}
    73  	return buffer.String()
    74  }
    75  

View as plain text