github.com/wangyougui/gf/v2@v2.6.5/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/wangyougui/gf. 6 7 // Package httputil provides HTTP functions for internal usage only. 8 package httputil 9 10 import ( 11 "net/http" 12 "strings" 13 14 "github.com/wangyougui/gf/v2/encoding/gurl" 15 "github.com/wangyougui/gf/v2/internal/empty" 16 "github.com/wangyougui/gf/v2/text/gstr" 17 "github.com/wangyougui/gf/v2/util/gconv" 18 ) 19 20 const ( 21 fileUploadingKey = "@file:" 22 ) 23 24 // BuildParams builds the request string for the http client. The `params` can be type of: 25 // string/[]byte/map/struct/*struct. 26 // 27 // The optional parameter `noUrlEncode` specifies whether ignore the url encoding for the data. 28 func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) { 29 // If given string/[]byte, converts and returns it directly as string. 30 switch v := params.(type) { 31 case string, []byte: 32 return gconv.String(params) 33 case []interface{}: 34 if len(v) > 0 { 35 params = v[0] 36 } else { 37 params = nil 38 } 39 } 40 // Else converts it to map and does the url encoding. 41 m, urlEncode := gconv.Map(params), true 42 if len(m) == 0 { 43 return gconv.String(params) 44 } 45 if len(noUrlEncode) == 1 { 46 urlEncode = !noUrlEncode[0] 47 } 48 // If there's file uploading, it ignores the url encoding. 49 if urlEncode { 50 for k, v := range m { 51 if gstr.Contains(k, fileUploadingKey) || gstr.Contains(gconv.String(v), fileUploadingKey) { 52 urlEncode = false 53 break 54 } 55 } 56 } 57 s := "" 58 for k, v := range m { 59 // Ignore nil attributes. 60 if empty.IsNil(v) { 61 continue 62 } 63 if len(encodedParamStr) > 0 { 64 encodedParamStr += "&" 65 } 66 s = gconv.String(v) 67 if urlEncode { 68 if strings.HasPrefix(s, fileUploadingKey) && len(s) > len(fileUploadingKey) { 69 // No url encoding if uploading file. 70 } else { 71 s = gurl.Encode(s) 72 } 73 } 74 encodedParamStr += k + "=" + s 75 } 76 return 77 } 78 79 // HeaderToMap coverts request headers to map. 80 func HeaderToMap(header http.Header) map[string]interface{} { 81 m := make(map[string]interface{}) 82 for k, v := range header { 83 if len(v) > 1 { 84 m[k] = v 85 } else if len(v) == 1 { 86 m[k] = v[0] 87 } 88 } 89 return m 90 }