http.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package util
  4. import (
  5. "bytes"
  6. "fmt"
  7. "io/ioutil"
  8. "github.com/gin-gonic/gin"
  9. jsoniter "github.com/json-iterator/go"
  10. )
  11. // 替换encoding/json包
  12. var json = jsoniter.ConfigCompatibleWithStandardLibrary
  13. // ShouldBind 统一进行http参数解析, header, path, query, body 可为nil
  14. func ShouldBind(ctx *gin.Context, header, path, query, body interface{}) error {
  15. // 解析header参数
  16. if header != nil {
  17. if err := ctx.ShouldBindHeader(header); err != nil {
  18. s, _ := json.MarshalToString(ctx.Request.Header)
  19. return fmt.Errorf("ctx.ShouldBindHeader, err: %+v, params: %s", err, s)
  20. }
  21. }
  22. // 解析path参数
  23. if path != nil {
  24. if err := ctx.ShouldBindUri(path); err != nil {
  25. s, _ := json.MarshalToString(ctx.FullPath)
  26. return fmt.Errorf("ctx.ShouldBindUri, err: %+v, params: %s", err, s)
  27. }
  28. }
  29. // 解析query参数
  30. if query != nil {
  31. if err := ctx.ShouldBindQuery(query); err != nil {
  32. s, _ := json.MarshalToString(ctx.Request.URL.RawQuery)
  33. return fmt.Errorf("ctx.ShouldBindQuery, err: %+v, params: %s", err, s)
  34. }
  35. }
  36. // 解析body参数
  37. if body != nil {
  38. // 读出body数据
  39. buf, err := ctx.GetRawData()
  40. if err == nil {
  41. ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buf)) // 关键: 回写body,便于后面使用
  42. }
  43. // 解析body参数,本方法会把body取完
  44. if err := ctx.ShouldBind(body); err != nil {
  45. return fmt.Errorf("ctx.ShouldBind, err: %+v, params: %s", err, string(buf))
  46. }
  47. }
  48. return nil
  49. }