Skip to content

Commit

Permalink
ezhttp: don't override 'Accept' header with RespondsJSON...()
Browse files Browse the repository at this point in the history
  • Loading branch information
joonas-fi committed Mar 6, 2023
1 parent 700c6fd commit 09a1dfa
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
4 changes: 3 additions & 1 deletion net/http/ezhttp/conffns.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions net/http/ezhttp/ezhttp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down

0 comments on commit 09a1dfa

Please sign in to comment.