requests.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. package httpx
  2. import (
  3. "io"
  4. "net/http"
  5. "strings"
  6. "github.com/tal-tech/go-zero/core/mapping"
  7. "github.com/tal-tech/go-zero/rest/internal/context"
  8. )
  9. const (
  10. formKey = "form"
  11. pathKey = "path"
  12. emptyJson = "{}"
  13. maxMemory = 32 << 20 // 32MB
  14. maxBodyLen = 8 << 20 // 8MB
  15. separator = ";"
  16. tokensInAttribute = 2
  17. )
  18. var (
  19. formUnmarshaler = mapping.NewUnmarshaler(formKey, mapping.WithStringValues())
  20. pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues())
  21. )
  22. func Parse(r *http.Request, v interface{}) error {
  23. if err := ParsePath(r, v); err != nil {
  24. return err
  25. }
  26. if err := ParseForm(r, v); err != nil {
  27. return err
  28. }
  29. return ParseJsonBody(r, v)
  30. }
  31. // Parses the form request.
  32. func ParseForm(r *http.Request, v interface{}) error {
  33. if err := r.ParseForm(); err != nil {
  34. return err
  35. }
  36. if err := r.ParseMultipartForm(maxMemory); err != nil {
  37. if err != http.ErrNotMultipart {
  38. return err
  39. }
  40. }
  41. params := make(map[string]interface{}, len(r.Form))
  42. for name := range r.Form {
  43. formValue := r.Form.Get(name)
  44. if len(formValue) > 0 {
  45. params[name] = formValue
  46. }
  47. }
  48. return formUnmarshaler.Unmarshal(params, v)
  49. }
  50. func ParseHeader(headerValue string) map[string]string {
  51. ret := make(map[string]string)
  52. fields := strings.Split(headerValue, separator)
  53. for _, field := range fields {
  54. field = strings.TrimSpace(field)
  55. if len(field) == 0 {
  56. continue
  57. }
  58. kv := strings.SplitN(field, "=", tokensInAttribute)
  59. if len(kv) != tokensInAttribute {
  60. continue
  61. }
  62. ret[kv[0]] = kv[1]
  63. }
  64. return ret
  65. }
  66. // Parses the post request which contains json in body.
  67. func ParseJsonBody(r *http.Request, v interface{}) error {
  68. var reader io.Reader
  69. if withJsonBody(r) {
  70. reader = io.LimitReader(r.Body, maxBodyLen)
  71. } else {
  72. reader = strings.NewReader(emptyJson)
  73. }
  74. return mapping.UnmarshalJsonReader(reader, v)
  75. }
  76. // Parses the symbols reside in url path.
  77. // Like http://localhost/bag/:name
  78. func ParsePath(r *http.Request, v interface{}) error {
  79. vars := context.Vars(r)
  80. m := make(map[string]interface{}, len(vars))
  81. for k, v := range vars {
  82. m[k] = v
  83. }
  84. return pathUnmarshaler.Unmarshal(m, v)
  85. }
  86. func withJsonBody(r *http.Request) bool {
  87. return r.ContentLength > 0 && strings.Contains(r.Header.Get(ContentType), ApplicationJson)
  88. }