Skip to content

Commit

Permalink
fix: support nest struct in StructToUrlValues
Browse files Browse the repository at this point in the history
  • Loading branch information
duke-git committed Apr 2, 2024
1 parent 5e6e8d8 commit 2a796ad
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 17 deletions.
14 changes: 11 additions & 3 deletions netutil/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import (
"strings"
"time"

"github.com/duke-git/lancet/v2/convertor"
"github.com/duke-git/lancet/v2/slice"
)

Expand Down Expand Up @@ -363,11 +362,20 @@ func validateRequest(req *HttpRequest) error {
// Play: https://go.dev/play/p/pFqMkM40w9z
func StructToUrlValues(targetStruct any) (url.Values, error) {
result := url.Values{}
s, err := convertor.StructToMap(targetStruct)

var m map[string]interface{}

jsonBytes, err := json.Marshal(targetStruct)
if err != nil {
return nil, err
}
for k, v := range s {

err = json.Unmarshal(jsonBytes, &m)
if err != nil {
return nil, err
}

for k, v := range m {
result.Add(k, fmt.Sprintf("%v", v))
}

Expand Down
28 changes: 14 additions & 14 deletions netutil/http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,16 +227,25 @@ func TestStructToUrlValues(t *testing.T) {

assert := internal.NewAssert(t, "TestStructToUrlValues")

type CommReq struct {
Version string `json:"version"`
}

type TodoQuery struct {
Id int `json:"id"`
UserId int `json:"userId"`
Name string `json:"name,omitempty"`
Id int `json:"id"`
UserId int `json:"userId"`
Name string `json:"name,omitempty"`
CommReq `json:",inline"`
}
item1 := TodoQuery{
Id: 1,
UserId: 123,
Name: "",
CommReq: CommReq{
Version: "1.0",
},
}

todoValues, err := StructToUrlValues(item1)
if err != nil {
t.Errorf("params is invalid: %v", err)
Expand All @@ -245,19 +254,10 @@ func TestStructToUrlValues(t *testing.T) {
assert.Equal("1", todoValues.Get("id"))
assert.Equal("123", todoValues.Get("userId"))
assert.Equal("", todoValues.Get("name"))

item2 := TodoQuery{
Id: 2,
UserId: 456,
}
queryValues2, _ := StructToUrlValues(item2)

assert.Equal("2", queryValues2.Get("id"))
assert.Equal("456", queryValues2.Get("userId"))
assert.Equal("", queryValues2.Get("name"))
assert.Equal("1.0", todoValues.Get("version"))
}

func handleFileRequest(t *testing.T, w http.ResponseWriter, r *http.Request) {
func handleFileRequest(t *testing.T, _ http.ResponseWriter, r *http.Request) {
err := r.ParseMultipartForm(1024)
if err != nil {
t.Fatal(err)
Expand Down

0 comments on commit 2a796ad

Please sign in to comment.