Skip to content

Commit

Permalink
fix: API response-headers compatibility with origin #131
Browse files Browse the repository at this point in the history
Signed-off-by: Son Bui <sonbv00@gmail.com>
  • Loading branch information
sonbui00 committed Aug 7, 2023
1 parent 62ec555 commit eae4786
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 4 deletions.
13 changes: 12 additions & 1 deletion httpbin/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,15 +314,26 @@ func (h *HTTPBin) Unstable(w http.ResponseWriter, r *http.Request) {
// ResponseHeaders responds with a map of header values
func (h *HTTPBin) ResponseHeaders(w http.ResponseWriter, r *http.Request) {
args := r.URL.Query()
body := make(map[string]interface{})
for k, vs := range args {
for _, v := range vs {
w.Header().Add(k, v)
}
if len(vs) == 1 {
body[k] = vs[0]
} else {
body[k] = vs
}
}
if contentType := w.Header().Get("Content-Type"); contentType == "" {
w.Header().Set("Content-Type", jsonContentType)
}
mustMarshalJSON(w, args)
body["Content-Type"] = w.Header().Get("Content-Type")
body["Content-Length"] = 0
buf := &bytes.Buffer{}
json.NewEncoder(buf).Encode(body)
body["Content-Length"] = buf.Len()
mustMarshalJSON(w, body)
}

func redirectLocation(r *http.Request, relative bool, n int) string {
Expand Down
22 changes: 19 additions & 3 deletions httpbin/handlers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1163,16 +1163,32 @@ func TestResponseHeaders(t *testing.T) {

req, _ := http.NewRequest("GET", fmt.Sprintf("%s/response-headers?%s", srv.URL, wantHeaders.Encode()), nil)
resp := must.DoReq(t, client, req)
result := mustParseResponse[http.Header](t, resp)

type bodyResponse struct {
Foo string `json:"Foo"`
Bar []string `json:"Bar"`
ContentType string `json:"Content-Type"`
ContentLength int `json:"Content-Length"`
}

result := mustParseResponse[bodyResponse](t, resp)

assert.ContentType(t, resp, result.ContentType)
assert.Equal[bool](t, result.ContentLength > 0, true, "JSON response Content-Length mismatch")

for k, expectedValues := range wantHeaders {
// expected headers should be present in the HTTP response itself
respValues := resp.Header[k]
assert.DeepEqual(t, respValues, expectedValues, "HTTP response headers mismatch")

// they should also be reflected in the decoded JSON resposne
resultValues := result[k]
assert.DeepEqual(t, resultValues, expectedValues, "JSON response headers mismatch")
if len(expectedValues) == 1 {
value := reflect.ValueOf(result).FieldByName(k).String()
assert.Equal[string](t, value, expectedValues[0], "JSON response headers mismatch")
} else {
value := reflect.ValueOf(result).FieldByName(k).Interface().([]string)
assert.DeepEqual(t, value, expectedValues, "JSON response headers mismatch")
}
}
})

Expand Down

0 comments on commit eae4786

Please sign in to comment.