123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- package common
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io/ioutil"
- "net/http"
- "net/url"
- "strings"
- )
- func CopyReqAndFormData(req *http.Request, copy ...bool) {
- //获取请求体内容
- bodyBytes, _ := ioutil.ReadAll(req.Body)
- _ = req.Body.Close()
- //将请求体内容重新写入请求体
- req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
- if strings.Index(req.Header.Get("Content-Type"), "json") > -1 {
- _ = ParseJson(req)
- } else {
- _ = req.ParseForm() //格式化请求内容
- }
- //将请求体内容重新写入请求体
- if len(copy) == 0 || copy[0] == false {
- req.Body = ioutil.NopCloser(bytes.NewBuffer(bodyBytes))
- }
- }
- func ParseJson(req *http.Request) error {
- bytes, err := ioutil.ReadAll(req.Body)
- if err != nil {
- return err
- }
- jsonMap := map[string]interface{}{}
- err = json.Unmarshal(bytes, &jsonMap)
- if err != nil {
- return err
- }
- req.Form = make(url.Values)
- for k, v := range jsonMap {
- req.Form.Set(k, fmt.Sprint(v))
- }
- return nil
- }
|