-
Notifications
You must be signed in to change notification settings - Fork 0
/
hydrate.go
68 lines (56 loc) · 1.31 KB
/
hydrate.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package coost
import (
"net/http"
"net/url"
"strings"
"time"
)
var defaultCookieLifespan = time.Hour * 24 * 30
const (
defaultPath = "/"
httpsScheme = "https"
cookieHeaderKey = "cookie-header"
keyValuePairsSep = "; "
keyValueSep = "="
)
func expandCookieHeader(cookieHeader string) map[string]string {
kvm := make(map[string]string)
kvps := strings.Split(cookieHeader, keyValuePairsSep)
for _, kvp := range kvps {
//TODO: Use strings.Cut in 1.18
kv := strings.Split(kvp, keyValueSep)
if len(kv) == 2 {
key := strings.TrimSpace(kv[0])
val := strings.TrimSpace(kv[1])
kvm[key] = val
}
}
return kvm
}
func hydrate(host string, cookies map[string]string) (*url.URL, []*http.Cookie) {
//replace cookie-header with extended values
if content, ok := cookies[cookieHeaderKey]; ok {
for key, value := range expandCookieHeader(content) {
cookies[key] = value
}
delete(cookies, cookieHeaderKey)
}
cs := make([]*http.Cookie, 0, len(cookies))
for name, value := range cookies {
ck := &http.Cookie{
Name: name,
Value: value,
Path: defaultPath,
Domain: host,
Expires: time.Now().Add(defaultCookieLifespan),
Secure: true,
HttpOnly: true,
}
cs = append(cs, ck)
}
u := &url.URL{
Scheme: httpsScheme,
Host: host,
}
return u, cs
}