-
Notifications
You must be signed in to change notification settings - Fork 0
/
export.go
75 lines (67 loc) · 1.34 KB
/
export.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
69
70
71
72
73
74
75
package kooky
import (
"fmt"
"io"
"net/http"
"strings"
)
const httpOnlyPrefix = `#HttpOnly_`
// ExportCookies() export "cookies" in the Netscape format.
//
// curl, wget, ... use this format.
func ExportCookies[T Cookie | http.Cookie](w io.Writer, cookies []*T) {
if len(cookies) < 1 {
return
}
var j int
for i, cookie := range cookies {
if cookie == nil {
continue
}
fmt.Fprint(w, "# HTTP Cookie File\n\n")
j = i
break
}
writeCookie := func(w io.Writer, cookie *http.Cookie) {
var domain string
if cookie.HttpOnly {
domain = httpOnlyPrefix
}
domain += cookie.Domain
fmt.Fprintf(
w,
"%s\t%s\t%s\t%s\t%d\t%s\t%s\n",
domain,
netscapeBool(strings.HasPrefix(cookie.Domain, `.`)),
cookie.Path,
netscapeBool(cookie.Secure),
cookie.Expires.Unix(),
cookie.Name,
cookie.Value,
)
}
// https://github.com/golang/go/issues/45380#issuecomment-1014950980
switch cookiesTyp := any(cookies).(type) {
case []*http.Cookie:
for i := j; i < len(cookiesTyp); i++ {
if cookiesTyp[i] == nil {
continue
}
writeCookie(w, cookiesTyp[i])
}
case []*Cookie:
for i := j; i < len(cookiesTyp); i++ {
if cookiesTyp[i] == nil {
continue
}
writeCookie(w, &cookiesTyp[i].Cookie)
}
}
}
type netscapeBool bool
func (b netscapeBool) String() string {
if b {
return `TRUE`
}
return `FALSE`
}