Skip to content

Instantly share code, notes, and snippets.

@rekby
Created September 7, 2022 22:57
Show Gist options
  • Save rekby/0c74915a620183118c2584a6d7182adb to your computer and use it in GitHub Desktop.
Save rekby/0c74915a620183118c2584a6d7182adb to your computer and use it in GitHub Desktop.
Use header.Values for check header instead of header.Get
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"strings"
)
const encodingHeader = "Accept-Encoding"
func isGzipByGet(header http.Header) bool {
return strings.Contains(header.Get(encodingHeader), "gzip")
}
func isGzipByValues(header http.Header) bool {
for _, v := range header.Values(encodingHeader) {
if v == "gzip" {
return true
}
}
return false
}
func main() {
server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
fmt.Println(request.URL)
fmt.Println("values:", request.Header.Values(encodingHeader))
fmt.Println("can gzip by get", isGzipByGet(request.Header))
fmt.Println("can gzip by values", isGzipByValues(request.Header))
fmt.Println()
}))
defer server.Close()
req, _ := http.NewRequest(http.MethodGet, server.URL+"/with-gzip-first-place", nil)
req.Header.Add(encodingHeader, "gzip")
req.Header.Add(encodingHeader, "asd")
_, _ = http.DefaultClient.Do(req)
req, _ = http.NewRequest(http.MethodGet, server.URL+"/with-gzip-second-place", nil)
req.Header.Add(encodingHeader, "asd")
req.Header.Add(encodingHeader, "gzip")
_, _ = http.DefaultClient.Do(req)
req, _ = http.NewRequest(http.MethodGet, server.URL+"/without-gzip", nil)
req.Header.Add(encodingHeader, "asd")
_, _ = http.DefaultClient.Do(req)
}
@rekby
Copy link
Author

rekby commented Sep 7, 2022

Output:
/with-gzip-first-place
values: [gzip asd]
can gzip by get true
can gzip by values true

/with-gzip-second-place
values: [asd gzip]
can gzip by get false
can gzip by values true

/without-gzip
values: [asd]
can gzip by get false
can gzip by values false

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment