http.go 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  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. )
  10. // ShouldBind 统一进行http参数解析, header, path, query, body 可为nil
  11. func ShouldBind(ctx *gin.Context, header, path, query, body interface{}) error {
  12. // 解析header参数
  13. if header != nil {
  14. if err := ctx.ShouldBindHeader(header); err != nil {
  15. s, _ := json.MarshalToString(ctx.Request.Header)
  16. return fmt.Errorf("ctx.ShouldBindHeader, err: %+v, params: %s", err, s)
  17. }
  18. }
  19. // 解析path参数
  20. if path != nil {
  21. if err := ctx.ShouldBindUri(path); err != nil {
  22. s, _ := json.MarshalToString(ctx.FullPath)
  23. return fmt.Errorf("ctx.ShouldBindUri, err: %+v, params: %s", err, s)
  24. }
  25. }
  26. // 解析query参数
  27. if query != nil {
  28. if err := ctx.ShouldBindQuery(query); err != nil {
  29. s, _ := json.MarshalToString(ctx.Request.URL.RawQuery)
  30. return fmt.Errorf("ctx.ShouldBindQuery, err: %+v, params: %s", err, s)
  31. }
  32. }
  33. // 解析body参数
  34. if body != nil {
  35. // 读出body数据
  36. buf, err := ctx.GetRawData()
  37. if err == nil {
  38. ctx.Request.Body = ioutil.NopCloser(bytes.NewBuffer(buf)) // 关键: 回写body,便于后面使用
  39. }
  40. // 解析body参数,本方法会把body取完
  41. if err := ctx.ShouldBind(&body); err != nil {
  42. return fmt.Errorf("ctx.ShouldBind, err: %+v, params: %s", err, string(buf))
  43. }
  44. }
  45. return nil
  46. }