Skip to content

Instantly share code, notes, and snippets.

@Integralist
Last active June 23, 2022 12:45
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Integralist/62b7ba713197ee331d80cb3479903ff3 to your computer and use it in GitHub Desktop.
[Go remove cookie from http.Request] #go #golang #http #cookie
// 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))
}
}
// 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