/
cookies.go
52 lines (40 loc) · 1.13 KB
/
cookies.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package writer
import (
"net/http"
"regexp"
"strings"
)
const (
SecureCookiesStrip = "strip"
SecureCookieAV = "Secure"
setCookieHeader = "Set-Cookie"
)
var regexSplitSetCookie = regexp.MustCompile(`([^;]+);?`)
func stripSecureCookies(header http.Header) {
list := header.Values(setCookieHeader)
header.Del(setCookieHeader)
for _, original := range list {
parts, isSecure := parseSetCookieHeader(original)
if !isSecure {
header.Add(setCookieHeader, original) // Unchanged
} else {
header.Add(setCookieHeader, strings.Join(parts, "; "))
}
}
}
// parseSetCookieHeader splits the given Set-Cookie HTTP header field value
// and always removes the <Secure> flag. If the <Secure> flag was present, the
// second return value is set to <true>, otherwise to <false>.
func parseSetCookieHeader(setCookie string) ([]string, bool) {
var parts []string
var isSecure bool
for _, m := range regexSplitSetCookie.FindAllStringSubmatch(setCookie, -1) {
part := strings.TrimSpace(m[1])
if strings.EqualFold(part, SecureCookieAV) {
isSecure = true
continue
}
parts = append(parts, part)
}
return parts, isSecure
}