gf/net/ghttp/ghttp_func.go

64 lines
1.6 KiB
Go
Raw Normal View History

// Copyright 2017 gf Author(https://github.com/gogf/gf). All Rights Reserved.
//
// 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,
// You can obtain one at https://github.com/gogf/gf.
package ghttp
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"
)
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.
m, urlEncode := gconv.Map(params), true
if len(m) == 0 {
return gconv.String(params)
}
2019-07-11 19:47:15 +08:00
if len(noUrlEncode) == 1 {
urlEncode = !noUrlEncode[0]
}
s := ""
2019-06-19 09:06:52 +08:00
for k, v := range m {
if len(encodedParamStr) > 0 {
encodedParamStr += "&"
}
s = gconv.String(v)
if urlEncode && len(s) > 6 && strings.Compare(s[0:6], "@file:") != 0 {
s = gurl.Encode(s)
2019-06-19 09:06:52 +08:00
}
encodedParamStr += k + "=" + s
2019-06-19 09:06:52 +08:00
}
return
}
2020-01-20 20:32:39 +08:00
// niceCallFunc calls function <f> with exception capture logic.
func niceCallFunc(f func()) {
defer func() {
if err := recover(); err != nil {
switch err {
case gEXCEPTION_EXIT:
fallthrough
case gEXCEPTION_EXIT_ALL:
return
default:
panic(err)
}
}
}()
f()
}