From 09a1dfabc4a78b332aef54fb237322fd7738a545 Mon Sep 17 00:00:00 2001 From: Joonas Loppi Date: Mon, 6 Mar 2023 14:40:41 +0200 Subject: [PATCH] ezhttp: don't override 'Accept' header with RespondsJSON...() --- net/http/ezhttp/conffns.go | 4 +++- net/http/ezhttp/ezhttp_test.go | 17 +++++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/net/http/ezhttp/conffns.go b/net/http/ezhttp/conffns.go index 0dcb51a..467b3ed 100644 --- a/net/http/ezhttp/conffns.go +++ b/net/http/ezhttp/conffns.go @@ -68,7 +68,9 @@ func RespondsJSONDisallowUnknownFields(obj interface{}) ConfigPiece { func respondsJSON(ref interface{}, allowUnknownFields bool) ConfigPiece { return After(func(conf *Config) { - conf.Request.Header.Set("Accept", jsonContentType) + if conf.Request.Header.Get("Accept") == "" { // don't override if we have explicit `Accept` header + conf.Request.Header.Set("Accept", jsonContentType) + } conf.OutputsJson = true conf.OutputsJsonRef = ref diff --git a/net/http/ezhttp/ezhttp_test.go b/net/http/ezhttp/ezhttp_test.go index 0a66116..61eda4a 100644 --- a/net/http/ezhttp/ezhttp_test.go +++ b/net/http/ezhttp/ezhttp_test.go @@ -150,6 +150,23 @@ func TestAuthBearer(t *testing.T) { assert.EqualString(t, string(respBody), "Echoing Authorization: Bearer LOLOLOLOL") } +func TestRespondsJSONDoesntOverrideExplicitAccept(t *testing.T) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, `{"AcceptEchoed": "%s"}`, r.Header.Get("Accept")) + })) + defer ts.Close() + + respJSON := struct { + AcceptEchoed string + }{} + + // before the fix, RespondsJSONDisallowUnknownFields() used to override explicit header + _, err := Get(context.TODO(), ts.URL, Header("Accept", "text/foobar"), RespondsJSONDisallowUnknownFields(&respJSON)) + assert.Ok(t, err) + + assert.EqualString(t, respJSON.AcceptEchoed, "text/foobar") +} + func TestAuthBasic(t *testing.T) { ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Echoing Authorization: %s", r.Header.Get("Authorization"))