2019-02-02 16:18:25 +08:00
|
|
|
// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
|
2018-01-11 16:06:42 +08:00
|
|
|
//
|
|
|
|
// This Source Code Form is subject to the terms of the MIT License.
|
|
|
|
// If a copy of the MIT was not distributed with this file,
|
2019-02-02 16:18:25 +08:00
|
|
|
// You can obtain one at https://github.com/gogf/gf.
|
2018-01-11 16:06:42 +08:00
|
|
|
|
|
|
|
package ghttp
|
|
|
|
|
2018-09-26 18:44:30 +08:00
|
|
|
import (
|
2019-07-11 19:47:15 +08:00
|
|
|
"strings"
|
|
|
|
|
2019-07-29 21:01:19 +08:00
|
|
|
"github.com/gogf/gf/encoding/gurl"
|
|
|
|
"github.com/gogf/gf/util/gconv"
|
2018-09-26 18:44:30 +08:00
|
|
|
)
|
2018-01-11 16:06:42 +08:00
|
|
|
|
2020-01-20 20:32:39 +08:00
|
|
|
// BuildParams builds the request string for the http client. The <params> can be type of:
|
|
|
|
// string/[]byte/map/struct/*struct.
|
|
|
|
//
|
|
|
|
// The optional parameter <noUrlEncode> specifies whether ignore the url encoding for the data.
|
2019-07-11 19:47:15 +08:00
|
|
|
func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) {
|
2020-01-20 20:32:39 +08:00
|
|
|
// If given string/[]byte, converts and returns it directly as string.
|
|
|
|
switch params.(type) {
|
|
|
|
case string, []byte:
|
|
|
|
return gconv.String(params)
|
|
|
|
}
|
|
|
|
// Else converts it to map and does the url encoding.
|
2019-07-11 10:02:44 +08:00
|
|
|
m, urlEncode := gconv.Map(params), true
|
2019-04-23 20:12:44 +08:00
|
|
|
if len(m) == 0 {
|
|
|
|
return gconv.String(params)
|
|
|
|
}
|
2019-07-11 19:47:15 +08:00
|
|
|
if len(noUrlEncode) == 1 {
|
|
|
|
urlEncode = !noUrlEncode[0]
|
2019-07-11 10:02:44 +08:00
|
|
|
}
|
2019-04-23 20:12:44 +08:00
|
|
|
s := ""
|
2019-06-19 09:06:52 +08:00
|
|
|
for k, v := range m {
|
|
|
|
if len(encodedParamStr) > 0 {
|
|
|
|
encodedParamStr += "&"
|
|
|
|
}
|
|
|
|
s = gconv.String(v)
|
2019-07-11 10:02:44 +08:00
|
|
|
if urlEncode && len(s) > 6 && strings.Compare(s[0:6], "@file:") != 0 {
|
|
|
|
s = gurl.Encode(s)
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
2019-07-11 10:02:44 +08:00
|
|
|
encodedParamStr += k + "=" + s
|
2019-06-19 09:06:52 +08:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2019-08-03 15:54:12 +08:00
|
|
|
|
2020-01-20 20:32:39 +08:00
|
|
|
// niceCallFunc calls function <f> with exception capture logic.
|
2019-08-03 15:54:12 +08:00
|
|
|
func niceCallFunc(f func()) {
|
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil {
|
|
|
|
switch err {
|
2020-03-04 17:29:23 +08:00
|
|
|
case gEXCEPTION_EXIT, gEXCEPTION_EXIT_ALL:
|
2019-08-03 15:54:12 +08:00
|
|
|
return
|
|
|
|
default:
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
f()
|
|
|
|
}
|