feat: httpx.Parse supports parsing structures that implement the Unmarshaler interface (#4143)

This commit is contained in:
Leo
2024-05-11 22:25:10 +08:00
committed by GitHub
parent 42b3bae65a
commit 040fee5669
2 changed files with 80 additions and 21 deletions

View File

@@ -1,6 +1,7 @@
package httpx
import (
"bytes"
"errors"
"net/http"
"net/http/httptest"
@@ -515,3 +516,23 @@ func (m mockRequest) Validate() error {
return nil
}
type mockCustomUnmarshalerStruct struct {
Name string
}
func (m *mockCustomUnmarshalerStruct) UnmarshalJSON(b []byte) error {
m.Name = string(b)
return nil
}
func TestCustomUnmarshalerStructRequest(t *testing.T) {
reqBody := `{"name": "hello"}`
r := httptest.NewRequest(http.MethodPost, "/a", bytes.NewReader([]byte(reqBody)))
r.Header.Set("Content-Type", "application/json")
v := struct {
Foo *mockCustomUnmarshalerStruct `json:"name"`
}{}
assert.Nil(t, Parse(r, &v))
assert.Equal(t, "hello", v.Foo.Name)
}