gitea源码

base_form.go 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. // Copyright 2024 The Gitea Authors. All rights reserved.
  2. // SPDX-License-Identifier: MIT
  3. package context
  4. import (
  5. "strconv"
  6. "strings"
  7. "code.gitea.io/gitea/modules/optional"
  8. "code.gitea.io/gitea/modules/util"
  9. )
  10. // FormString returns the first value matching the provided key in the form as a string
  11. // It works the same as http.Request.FormValue:
  12. // try urlencoded request body first, then query string, then multipart form body
  13. func (b *Base) FormString(key string, def ...string) string {
  14. s := b.Req.FormValue(key)
  15. if s == "" {
  16. s = util.OptionalArg(def)
  17. }
  18. return s
  19. }
  20. // FormStrings returns a values for the key in the form (including query parameters), similar to FormString
  21. func (b *Base) FormStrings(key string) []string {
  22. if b.Req.Form == nil {
  23. if err := b.Req.ParseMultipartForm(32 << 20); err != nil {
  24. return nil
  25. }
  26. }
  27. if v, ok := b.Req.Form[key]; ok {
  28. return v
  29. }
  30. return nil
  31. }
  32. // FormTrim returns the first value for the provided key in the form as a space trimmed string
  33. func (b *Base) FormTrim(key string) string {
  34. return strings.TrimSpace(b.Req.FormValue(key))
  35. }
  36. // FormInt returns the first value for the provided key in the form as an int
  37. func (b *Base) FormInt(key string) int {
  38. v, _ := strconv.Atoi(b.Req.FormValue(key))
  39. return v
  40. }
  41. // FormInt64 returns the first value for the provided key in the form as an int64
  42. func (b *Base) FormInt64(key string) int64 {
  43. v, _ := strconv.ParseInt(b.Req.FormValue(key), 10, 64)
  44. return v
  45. }
  46. // FormBool returns true if the value for the provided key in the form is "1", "true" or "on"
  47. func (b *Base) FormBool(key string) bool {
  48. s := b.Req.FormValue(key)
  49. v, _ := strconv.ParseBool(s)
  50. v = v || strings.EqualFold(s, "on")
  51. return v
  52. }
  53. // FormOptionalBool returns an optional.Some(true) or optional.Some(false) if the value
  54. // for the provided key exists in the form else it returns optional.None[bool]()
  55. func (b *Base) FormOptionalBool(key string) optional.Option[bool] {
  56. value := b.Req.FormValue(key)
  57. if len(value) == 0 {
  58. return optional.None[bool]()
  59. }
  60. s := b.Req.FormValue(key)
  61. v, _ := strconv.ParseBool(s)
  62. v = v || strings.EqualFold(s, "on")
  63. return optional.Some(v)
  64. }
  65. func (b *Base) SetFormString(key, value string) {
  66. _ = b.Req.FormValue(key) // force parse form
  67. b.Req.Form.Set(key, value)
  68. }