diff --git a/httpbin/handlers.go b/httpbin/handlers.go index 0755a83d..157ca930 100644 --- a/httpbin/handlers.go +++ b/httpbin/handlers.go @@ -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 { diff --git a/httpbin/handlers_test.go b/httpbin/handlers_test.go index 716dd697..ce4a070a 100644 --- a/httpbin/handlers_test.go +++ b/httpbin/handlers_test.go @@ -1163,7 +1163,18 @@ 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 @@ -1171,8 +1182,13 @@ func TestResponseHeaders(t *testing.T) { 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") + } } })