Skip to content

Commit 09a1dfa

Browse files
committed
ezhttp: don't override 'Accept' header with RespondsJSON...()
1 parent 700c6fd commit 09a1dfa

2 files changed

Lines changed: 20 additions & 1 deletion

File tree

net/http/ezhttp/conffns.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,9 @@ func RespondsJSONDisallowUnknownFields(obj interface{}) ConfigPiece {
6868

6969
func respondsJSON(ref interface{}, allowUnknownFields bool) ConfigPiece {
7070
return After(func(conf *Config) {
71-
conf.Request.Header.Set("Accept", jsonContentType)
71+
if conf.Request.Header.Get("Accept") == "" { // don't override if we have explicit `Accept` header
72+
conf.Request.Header.Set("Accept", jsonContentType)
73+
}
7274

7375
conf.OutputsJson = true
7476
conf.OutputsJsonRef = ref

net/http/ezhttp/ezhttp_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,23 @@ func TestAuthBearer(t *testing.T) {
150150
assert.EqualString(t, string(respBody), "Echoing Authorization: Bearer LOLOLOLOL")
151151
}
152152

153+
func TestRespondsJSONDoesntOverrideExplicitAccept(t *testing.T) {
154+
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
155+
fmt.Fprintf(w, `{"AcceptEchoed": "%s"}`, r.Header.Get("Accept"))
156+
}))
157+
defer ts.Close()
158+
159+
respJSON := struct {
160+
AcceptEchoed string
161+
}{}
162+
163+
// before the fix, RespondsJSONDisallowUnknownFields() used to override explicit header
164+
_, err := Get(context.TODO(), ts.URL, Header("Accept", "text/foobar"), RespondsJSONDisallowUnknownFields(&respJSON))
165+
assert.Ok(t, err)
166+
167+
assert.EqualString(t, respJSON.AcceptEchoed, "text/foobar")
168+
}
169+
153170
func TestAuthBasic(t *testing.T) {
154171
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
155172
fmt.Fprintf(w, "Echoing Authorization: %s", r.Header.Get("Authorization"))

0 commit comments

Comments
 (0)