github.com/gogf/gf@v1.16.9/net/ghttp/internal/httputil/httputils.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/gogf/gf. 6 7 package httputil 8 9 import ( 10 "github.com/gogf/gf/text/gstr" 11 "net/http" 12 "strings" 13 14 "github.com/gogf/gf/encoding/gurl" 15 "github.com/gogf/gf/util/gconv" 16 ) 17 18 const ( 19 fileUploadingKey = "@file:" 20 ) 21 22 // BuildParams builds the request string for the http client. The <params> can be type of: 23 // string/[]byte/map/struct/*struct. 24 // 25 // The optional parameter <noUrlEncode> specifies whether ignore the url encoding for the data. 26 func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) { 27 // If given string/[]byte, converts and returns it directly as string. 28 switch v := params.(type) { 29 case string, []byte: 30 return gconv.String(params) 31 case []interface{}: 32 if len(v) > 0 { 33 params = v[0] 34 } else { 35 params = nil 36 } 37 } 38 // Else converts it to map and does the url encoding. 39 m, urlEncode := gconv.Map(params), true 40 if len(m) == 0 { 41 return gconv.String(params) 42 } 43 if len(noUrlEncode) == 1 { 44 urlEncode = !noUrlEncode[0] 45 } 46 // If there's file uploading, it ignores the url encoding. 47 if urlEncode { 48 for k, v := range m { 49 if gstr.Contains(k, fileUploadingKey) || gstr.Contains(gconv.String(v), fileUploadingKey) { 50 urlEncode = false 51 break 52 } 53 } 54 } 55 s := "" 56 for k, v := range m { 57 if len(encodedParamStr) > 0 { 58 encodedParamStr += "&" 59 } 60 s = gconv.String(v) 61 if urlEncode && len(s) > 6 && strings.Compare(s[0:6], fileUploadingKey) != 0 { 62 s = gurl.Encode(s) 63 } 64 encodedParamStr += k + "=" + s 65 } 66 return 67 } 68 69 // HeaderToMap coverts request headers to map. 70 func HeaderToMap(header http.Header) map[string]interface{} { 71 m := make(map[string]interface{}) 72 for k, v := range header { 73 if len(v) > 1 { 74 m[k] = v 75 } else { 76 m[k] = v[0] 77 } 78 } 79 return m 80 }