improve ghttp.BuildParams

This commit is contained in:
John
2020-01-20 20:32:39 +08:00
parent 665b5960c8
commit 01b06e0745
2 changed files with 19 additions and 11 deletions

View File

@ -13,9 +13,17 @@ import (
"github.com/gogf/gf/util/gconv"
)
// 构建请求参数参数支持任意数据类型常见参数类型为string/map。
// 如果参数为map类型参数值将会进行urlencode编码可以通过 noUrlEncode:true 参数取消编码。
// 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.
func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr string) {
// 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)
@ -37,7 +45,7 @@ func BuildParams(params interface{}, noUrlEncode ...bool) (encodedParamStr strin
return
}
// 友好地调用方法
// niceCallFunc calls function <f> with exception capture logic.
func niceCallFunc(f func()) {
defer func() {
if err := recover(); err != nil {

View File

@ -228,7 +228,7 @@ func Test_Params_Basic(t *testing.T) {
r.Response.Write(m["name"])
return
}
if m := r.GetPostMap(); len(m) > 0 {
if m := r.GetMap(); len(m) > 0 {
r.Response.Write(m["name"])
return
}
@ -247,20 +247,20 @@ func Test_Params_Basic(t *testing.T) {
s.BindHandler("/struct", func(r *ghttp.Request) {
if m := r.GetQueryMap(); len(m) > 0 {
user := new(User)
r.GetQueryToStruct(user)
r.GetQueryStruct(user)
r.Response.Write(user.Id, user.Name, user.Pass1, user.Pass2)
return
}
if m := r.GetPostMap(); len(m) > 0 {
if m := r.GetMap(); len(m) > 0 {
user := new(User)
r.GetPostToStruct(user)
r.GetStruct(user)
r.Response.Write(user.Id, user.Name, user.Pass1, user.Pass2)
return
}
})
s.BindHandler("/struct-with-nil", func(r *ghttp.Request) {
user := (*User)(nil)
err := r.GetPostToStruct(&user)
err := r.GetStruct(&user)
r.Response.Write(err)
})
s.BindHandler("/struct-with-base", func(r *ghttp.Request) {
@ -278,11 +278,11 @@ func Test_Params_Basic(t *testing.T) {
Name string
Pass Base
}
if m := r.GetPostMap(); len(m) > 0 {
if m := r.GetMap(); len(m) > 0 {
user1 := new(UserWithBase1)
user2 := new(UserWithBase2)
r.GetToStruct(user1)
r.GetToStruct(user2)
r.GetStruct(user1)
r.GetStruct(user2)
r.Response.Write(user1.Id, user1.Name, user1.Pass1, user1.Pass2)
r.Response.Write(user2.Id, user2.Name, user2.Pass.Pass1, user2.Pass.Pass2)
}