path_processor.go 1.8 KB

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