Skip to content

Commit d6e9454

Browse files
committed
fix: Call to serializer even when response is nil
1 parent f9702d2 commit d6e9454

File tree

2 files changed

+35
-2
lines changed

2 files changed

+35
-2
lines changed

http.go

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,10 @@ func DefaultDeserialize(ctx context.Context, r io.Reader, v interface{}) error {
3535

3636
func DefaultSerialize(ctx context.Context, w io.Writer, v interface{}) error {
3737
resp := GetBoxContext(ctx).Response
38+
if v == nil {
39+
resp.WriteHeader(http.StatusNoContent)
40+
return nil
41+
}
3842
resp.Header().Set("Content-Type", "application/json")
3943
return json.NewEncoder(w).Encode(v)
4044
}
@@ -192,8 +196,7 @@ func Box2Http(b *B) http.Handler {
192196
}
193197

194198
if isNil(genericResponse) {
195-
// TODO: write empty response
196-
return
199+
genericResponse = nil
197200
}
198201

199202
err := b.Serializer(ctx, c.Response, genericResponse)

http_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,3 +172,33 @@ func TestBox2Http_customDeserializer(t *testing.T) {
172172
})
173173

174174
}
175+
176+
func TestBox2Http_customDeserializer_emptyResponse(t *testing.T) {
177+
178+
b := NewBox()
179+
b.Serializer = func(ctx context.Context, w io.Writer, v interface{}) error {
180+
resp := GetResponse(ctx)
181+
if v == nil {
182+
resp.WriteHeader(http.StatusNoContent)
183+
return nil
184+
}
185+
186+
resp.WriteHeader(http.StatusFound)
187+
return nil
188+
}
189+
type MyResponse struct {
190+
Name string `json:"name"`
191+
}
192+
b.Handle("GET", "/hello", func(w http.ResponseWriter, r *http.Request) *MyResponse {
193+
w.Header().Set("My-Header", "My value")
194+
return nil
195+
})
196+
s := httptest.NewServer(b)
197+
198+
res, _ := http.Get(s.URL + "/hello")
199+
AssertEqual(t, res.StatusCode, http.StatusNoContent)
200+
AssertEqual(t, res.Header.Get("My-Header"), "My value")
201+
body, _ := io.ReadAll(res.Body)
202+
AssertEqual(t, string(body), "")
203+
204+
}

0 commit comments

Comments
 (0)