gitea源码

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package context
  4. import (
  5. "net/url"
  6. "strconv"
  7. "strings"
  8. "code.gitea.io/gitea/modules/setting"
  9. "github.com/go-chi/chi/v5"
  10. )
  11. // PathParam returns the param in request path, eg: "/{var}" => "/a%2fb", then `var == "a/b"`
  12. func (b *Base) PathParam(name string) string {
  13. s, err := url.PathUnescape(b.PathParamRaw(name))
  14. if err != nil && !setting.IsProd {
  15. panic("Failed to unescape path param: " + err.Error() + ", there seems to be a double-unescaping bug")
  16. }
  17. return s
  18. }
  19. // PathParamRaw returns the raw param in request path, eg: "/{var}" => "/a%2fb", then `var == "a%2fb"`
  20. func (b *Base) PathParamRaw(name string) string {
  21. if strings.HasPrefix(name, ":") {
  22. setting.PanicInDevOrTesting("path param should not start with ':'")
  23. name = name[1:]
  24. }
  25. return chi.URLParam(b.Req, name)
  26. }
  27. // PathParamInt64 returns the param in request path as int64
  28. func (b *Base) PathParamInt64(p string) int64 {
  29. v, _ := strconv.ParseInt(b.PathParam(p), 10, 64)
  30. return v
  31. }
  32. // SetPathParam set request path params into routes
  33. func (b *Base) SetPathParam(name, value string) {
  34. if strings.HasPrefix(name, ":") {
  35. setting.PanicInDevOrTesting("path param should not start with ':'")
  36. name = name[1:]
  37. }
  38. chi.RouteContext(b).URLParams.Add(name, url.PathEscape(value))
  39. }