Skip to content

Commit 7f77fb7

Browse files
authored
GetJSONBody already takes in a pointer to the body (#44)
* GetJSONBody handle 'null': json.Unmarshal doesn't call custom unmarshalers if the body is 'null' * body is already a pointer
1 parent fce8e23 commit 7f77fb7

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

httputil/body.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ func GetJSONBody(r io.Reader, body any) error {
1515
return ErrMissingBody
1616
}
1717

18-
err := json.NewDecoder(r).Decode(&body)
18+
err := json.NewDecoder(r).Decode(body)
1919
if err == nil {
2020
return nil
2121
}

httputil/body_test.go

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,14 @@ func strP(s string) *string {
4747
return &s
4848
}
4949

50+
type BadIOReader struct {
51+
err error
52+
}
53+
54+
func (r *BadIOReader) Read(p []byte) (n int, err error) {
55+
return 0, r.err
56+
}
57+
5058
func TestGetJSONBody(t *testing.T) {
5159
tests := []struct {
5260
name string
@@ -57,16 +65,21 @@ func TestGetJSONBody(t *testing.T) {
5765
}{
5866
{"no body", nil, nil, nil, true},
5967
{"string", bytes.NewBufferString(`"foo"`), strP(""), strP("foo"), false},
60-
{"invalid json", bytes.NewBufferString(`{"foo"`), "", "", true},
61-
{"empty", bytes.NewBufferString(``), "", "", true},
68+
{"invalid json", bytes.NewBufferString(`{"foo"`), strP(""), strP(""), true},
69+
{"empty", bytes.NewBufferString(``), strP(""), strP(""), true},
70+
{"EOF", &BadIOReader{io.EOF}, strP(""), strP(""), true},
71+
{"read error", &BadIOReader{io.ErrClosedPipe}, strP(""), strP(""), true},
72+
{"null body", bytes.NewBufferString(`null`), &TestObject{}, &TestObject{}, true},
6273
{"validation error - bad ID type", bytes.NewBufferString(`{"ID":1}`), &TestObject{}, &TestObject{}, true},
6374
{"validations error - no ID", bytes.NewBufferString(`{}`), &TestObject{}, &TestObject{}, true},
6475
{"good", bytes.NewBufferString(`{"ID":"1"}`), &TestObject{}, &TestObject{ID: "1"}, false},
6576
}
6677
for _, tt := range tests {
6778
t.Run(tt.name, func(t *testing.T) {
6879
err := GetJSONBody(tt.r, tt.body)
69-
if !tt.wantErr {
80+
if tt.wantErr {
81+
require.Error(t, err)
82+
} else {
7083
require.NoError(t, err)
7184
}
7285

0 commit comments

Comments
 (0)