chore: coding style and comments (#1361)

* chore: coding style and comments

* chore: optimize `ParseJsonBody` (#1353)

* chore: optimize `ParseJsonBody`

* chore: optimize `ParseJsonBody`

* fix: fix a test

* chore: optimize `ParseJsonBody`

* fix a test

* chore: add comment

* chore: refactor

Co-authored-by: chenquan <chenquan.dev@foxmail.com>
This commit is contained in:
Kevin Wan
2021-12-22 21:43:37 +08:00
committed by GitHub
parent 263e426ae1
commit cd289465fd
7 changed files with 54 additions and 22 deletions

View File

@@ -25,8 +25,6 @@ var (
pathUnmarshaler = mapping.NewUnmarshaler(pathKey, mapping.WithStringValues())
headerUnmarshaler = mapping.NewUnmarshaler(headerKey, mapping.WithStringValues(),
mapping.WithCanonicalKeyFunc(textproto.CanonicalMIMEHeaderKey))
emptyMap = map[string]interface{}{}
)
// Parse parses the request.
@@ -107,13 +105,12 @@ func ParseHeader(headerValue string) map[string]string {
// ParseJsonBody parses the post request which contains json in body.
func ParseJsonBody(r *http.Request, v interface{}) error {
var reader io.Reader
if withJsonBody(r) {
reader = io.LimitReader(r.Body, maxBodyLen)
reader := io.LimitReader(r.Body, maxBodyLen)
return mapping.UnmarshalJsonReader(reader, v)
}
return mapping.UnmarshalJsonMap(emptyMap, v)
return mapping.UnmarshalJsonMap(nil, v)
}
// ParsePath parses the symbols reside in url path.

View File

@@ -196,9 +196,7 @@ Content-Disposition: form-data; name="age"
}
func TestParseJsonBody(t *testing.T) {
t.Run("has body", func(t *testing.T) {
var v struct {
Name string `json:"name"`
Age int `json:"age"`
@@ -211,11 +209,9 @@ func TestParseJsonBody(t *testing.T) {
assert.Nil(t, Parse(r, &v))
assert.Equal(t, "kevin", v.Name)
assert.Equal(t, 18, v.Age)
})
t.Run("hasn't body", func(t *testing.T) {
var v struct {
Name string `json:"name,optional"`
Age int `json:"age,optional"`
@@ -225,9 +221,7 @@ func TestParseJsonBody(t *testing.T) {
assert.Nil(t, Parse(r, &v))
assert.Equal(t, "", v.Name)
assert.Equal(t, 0, v.Age)
})
}
func TestParseRequired(t *testing.T) {