Skip to content

Commit

Permalink
[pref] #38 支持query模式下slice join string (#40)
Browse files Browse the repository at this point in the history
* [pref] #38 支持query模式下slice join string

* [fix] #38 修复错误的func命名

* [pref] #38 内联处理query参数
  • Loading branch information
RunsTp authored Apr 4, 2024
1 parent a3dc96f commit 67995f8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
8 changes: 8 additions & 0 deletions util.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,14 @@ func withParams(r *resty.Request, in any) error {
for name := range tagMap {
switch name {
case "query":
// 对query类型的字段进行特殊处理
if fieldType.Type.Kind() == reflect.Slice {
strSlice := make([]string, 0, 4)
for i := 0; i < fieldValue.Len(); i++ {
strSlice = append(strSlice, cast.ToString(fieldValue.Index(i).Interface()))
}
realVal = strings.Join(strSlice, ",")
}
contentType = "application/x-www-form-urlencoded"
case "json":
contentType = "application/json"
Expand Down
32 changes: 32 additions & 0 deletions util_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,38 @@ func TestFormData(t *testing.T) {
}
}

func TestWithParamsSlice(t *testing.T) {
type Test struct {
Ids []int `request:"query"`
IdsA []string `request:"query"`
}

params := Test{
Ids: []int{1, 2, 3},
IdsA: []string{"1", "2", "3"},
}

r := resty.New().R()
err := withParams(r, params)

if err != nil {
t.Fatal(err)
return
}

query := make(map[string]string)
for k := range r.QueryParam {
query[k] = r.QueryParam.Get(k)
}

if !maps.Equal(query, map[string]string{
"ids": "1,2,3",
"ids_a": "1,2,3",
}) {
t.Fatal("withParams query result not correct ", r.QueryParam)
}
}

func TestWithParamsNil(t *testing.T) {
r := resty.New().R()
err := withParams(r, []int{1, 2, 3})
Expand Down

0 comments on commit 67995f8

Please sign in to comment.