input_holder.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. // Param is a single URL parameter, consisting of a key and a value.
  6. type Param struct {
  7. Key string
  8. Value string
  9. }
  10. // Params is a Param-slice, as returned by the router.
  11. // The slice is ordered, the first URL parameter is also the first slice value.
  12. // It is therefore safe to read values by the index.
  13. type Params []Param
  14. // ByName returns the value of the first Param which key matches the given name.
  15. // If no matching Param is found, an empty string is returned.
  16. func (ps Params) ByName(name string) string {
  17. for _, entry := range ps {
  18. if entry.Key == name {
  19. return entry.Value
  20. }
  21. }
  22. return ""
  23. }
  24. type inputHolder struct {
  25. context *Context
  26. }
  27. func (i inputHolder) FromGET(key string) (va string) {
  28. va, _ = i.fromGET(key)
  29. return
  30. }
  31. func (i inputHolder) FromPOST(key string) (va string) {
  32. va, _ = i.fromPOST(key)
  33. return
  34. }
  35. func (i inputHolder) Get(key string) string {
  36. if value, exists := i.fromPOST(key); exists {
  37. return value
  38. }
  39. if value, exists := i.fromGET(key); exists {
  40. return value
  41. }
  42. return ""
  43. }
  44. func (i inputHolder) fromGET(key string) (string, bool) {
  45. req := i.context.Request
  46. req.ParseForm()
  47. if values, ok := req.Form[key]; ok && len(values) > 0 {
  48. return values[0], true
  49. }
  50. return "", false
  51. }
  52. func (i inputHolder) fromPOST(key string) (string, bool) {
  53. req := i.context.Request
  54. req.ParseForm()
  55. if values, ok := req.PostForm[key]; ok && len(values) > 0 {
  56. return values[0], true
  57. }
  58. return "", false
  59. }