« Back to Index

Go: remove cookie from http.Request

View original Gist on GitHub

Tags: #go #http

1. GOOD main.go

// 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))
	}
}

2. BAD main.go

// 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]
}