Skip to content

Commit

Permalink
append writeheader to fix custom headers (GO-7710) (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
jfallis authored May 16, 2023
1 parent 4e9090b commit 6518cbe
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 10 deletions.
8 changes: 2 additions & 6 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,18 +54,14 @@ func LambdaAdapter(l LambdaHandler) func(http.ResponseWriter, *http.Request) {
}
}

if resp.Headers == nil {
resp.Headers = make(map[string]string)
}
resp.Headers["Content-Type"] = "application/json"
w.WriteHeader(resp.StatusCode)
w.Header().Set("Content-Type", "application/json")
for k, v := range resp.Headers {
w.Header().Set(k, v)
}
for k, v := range resp.MultiValueHeaders {
w.Header().Set(k, strings.Join(v, ","))
}

w.WriteHeader(resp.StatusCode)
if _, wErr := w.Write([]byte(resp.Body)); wErr != nil {
panic(wErr)
}
Expand Down
8 changes: 4 additions & 4 deletions http_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,11 @@ func TestLambdaAdapter(t *testing.T) {

w := httptest.NewRecorder()
r := httptest.NewRequest(http.MethodGet, "/test/url/path/var1/var2", nil)
r.Header.Set("Content-Type", "application/json")
r.Header.Set("Content-Type", "text/plain")
g8.LambdaAdapter(l)(w, r)

assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
assert.Equal(t, "text/plain", w.Header().Get("Content-Type"))
assert.Equal(t, "cookie1,cookie2", w.Header().Get("Set-Cookie"))
assert.Equal(t, "success", w.Body.String())
}
Expand All @@ -44,7 +44,7 @@ func TestLambdaAdapter_without_content_type(t *testing.T) {
return &events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
MultiValueHeaders: map[string][]string{"Set-Cookie": {"cookie1", "cookie2"}},
Body: "success",
Body: `{"message":"success"}`,
}, nil
},
Method: http.MethodGet,
Expand All @@ -59,7 +59,7 @@ func TestLambdaAdapter_without_content_type(t *testing.T) {
assert.Equal(t, http.StatusOK, w.Code)
assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
assert.Equal(t, "cookie1,cookie2", w.Header().Get("Set-Cookie"))
assert.Equal(t, "success", w.Body.String())
assert.Equal(t, `{"message":"success"}`, w.Body.String())
}

func TestLambdaAdapter_g8_error(t *testing.T) {
Expand Down

0 comments on commit 6518cbe

Please sign in to comment.