Last active
June 23, 2022 12:45
Star
You must be signed in to star a gist
[Go remove cookie from http.Request] #go #golang #http #cookie
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
// For proxy situations where you want to strip a cookie from the incoming request at the proxy layer, before proxying it onto the actual backend. | |
package main | |
import ( | |
"fmt" | |
"net/http" | |
) | |
func main() { | |
req := &http.Request{ | |
Header: make(http.Header), | |
} | |
req.Header.Add("Cookie", "name1=value; name2=value2; name3=value3") | |
fmt.Printf("%+v\n", req.Header) | |
FilterClientCookies(req, "name2") | |
fmt.Printf("%+v\n", req.Header) | |
} | |
// FilterClientCookies removes a list of cookies from the "Cookie" request header by name. | |
func FilterClientCookies(r *http.Request, names ...string) { | |
filter := make(map[string]struct{}, len(names)) | |
for _, name := range names { | |
filter[name] = struct{}{} | |
} | |
cookies := r.Cookies() | |
r.Header.Del("Cookie") | |
for _, c := range cookies { | |
if _, ok := filter[c.Name]; ok { | |
continue | |
} | |
r.Header.Add("Cookie", fmt.Sprintf("%s=%s", c.Name, c.Value)) | |
} | |
} |
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
// For proxy situations where you want to strip a cookie from the incoming request at the proxy layer, before proxying it onto the actual backend. | |
package main | |
import ( | |
"fmt" | |
"net/http" | |
"strings" | |
) | |
func main() { | |
h := make(http.Header) | |
h.Add("Cookie", "name1=value; name2=value2; name3=value3") | |
fmt.Printf("%+v\n", h) | |
cs := strings.Split(h.Get("Cookie"), ";") | |
h.Del("Cookie") | |
cookieToRemove := "name2" | |
for _, c := range cs { | |
s := strings.TrimSpace(c) | |
if strings.HasPrefix(s, fmt.Sprintf("%s=", cookieToRemove)) { | |
continue | |
} | |
h.Add("Cookie", s) | |
} | |
fmt.Printf("%+v\n", h) | |
} | |
func removeFromSlice(s []string, i int) []string { | |
s[i] = s[len(s)-1] | |
return s[:len(s)-1] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment