Created
September 7, 2022 22:57
-
-
Save rekby/0c74915a620183118c2584a6d7182adb to your computer and use it in GitHub Desktop.
Use header.Values for check header instead of header.Get
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
Author
rekby
commented
Sep 7, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment