Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Vary: Accept-encoding header is duplicated if inner handler sets it #90

Open
austin-searchpilot opened this issue Sep 12, 2019 · 2 comments

Comments

@austin-searchpilot
Copy link

If the inner HTTP handler sets a Vary: Accept-Encoding header, then as the gzip middleware will always add in the same header, the output will have two identical headers.

Here is a failing test case:

func TestEnsureVaryHeaderNoDuplicate(t *testing.T) {
	handler := GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Add(vary, acceptEncoding)
		w.Write([]byte("test"))
		w.(io.Closer).Close()
	}))

	req := httptest.NewRequest("GET", "/", nil)
	req.Header.Set(acceptEncoding, "gzip")
	w := httptest.NewRecorder()
	handler.ServeHTTP(w, req)
	assert.Equal(t, w.Header()[vary], []string{acceptEncoding})
}

I don't think the HTTP spec explicitly disallows you from having the same key/value appearing twice in the headers but it feels tidier to only have one instance of it.

@jameshartig
Copy link
Contributor

I'm not sure there's a great way to fix this because technically the gziphandler package is adding the header BEFORE your inner handler, so technically your inner handler should be checking if the header already exists like so:

// if something else already set Vary: Accept-Encoding, don't set it twice
if !strings.Contains(w.Header().Get(vary), acceptEncoding) {
    w.Header().Add(vary, acceptEncoding)
}

@renthraysk
Copy link

Get() only returns the first element of a slice. Have to iterate over the slice. Also use canonical values.

func AddVary(w http.ResponseWriter, value string) {
	value = textproto.CanonicalMIMEHeaderKey(value)
	for _, v := range w.Header()["Vary"] {
		if textproto.CanonicalMIMEHeaderKey(v) == value {
			return
		}
	}
	w.Header().Add("Vary", value)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants