util.go 981 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "fmt"
  6. "io/ioutil"
  7. "net/http"
  8. "net/url"
  9. "strings"
  10. )
  11. func CopyReqAndFormData(req *http.Request, copy ...bool) {
  12. //获取请求体内容
  13. bodyBytes, _ := ioutil.ReadAll(req.Body)
  14. _ = req.Body.Close()
  15. //将请求体内容重新写入请求体
  16. req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
  17. if strings.Index(req.Header.Get("Content-Type"), "json") > -1 {
  18. _ = ParseJson(req)
  19. } else {
  20. _ = req.ParseForm() //格式化请求内容
  21. }
  22. //将请求体内容重新写入请求体
  23. if len(copy) == 0 || copy[0] == false {
  24. req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
  25. }
  26. }
  27. func ParseJson(req *http.Request) error {
  28. bytes, err := ioutil.ReadAll(req.Body)
  29. if err != nil {
  30. return err
  31. }
  32. jsonMap := map[string]interface{}{}
  33. err = json.Unmarshal(bytes, &jsonMap)
  34. if err != nil {
  35. return err
  36. }
  37. req.Form = make(url.Values)
  38. for k, v := range jsonMap {
  39. req.Form.Set(k, fmt.Sprint(v))
  40. }
  41. return nil
  42. }