-
Notifications
You must be signed in to change notification settings - Fork 2
/
persistent_jar_example_test.go
75 lines (61 loc) · 1.55 KB
/
persistent_jar_example_test.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 cookiejar_test
import (
"fmt"
"log"
"net/http"
"net/http/httptest"
"net/url"
"os"
"path/filepath"
"go.nhat.io/cookiejar"
)
func ExampleNewPersistentJar() {
tempDir, err := os.MkdirTemp(os.TempDir(), "example")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(tempDir)
cookiesFile := filepath.Join(tempDir, "cookies")
// Start a server to give us cookies.
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if cookie, err := r.Cookie("Flavor"); err != nil {
http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
} else {
cookie.Value = "Oatmeal Raisin"
http.SetCookie(w, cookie)
}
}))
defer ts.Close()
u, err := url.Parse(ts.URL)
if err != nil {
log.Fatal(err)
}
jar := cookiejar.NewPersistentJar(
cookiejar.WithFilePath(cookiesFile),
cookiejar.WithAutoSync(true),
// All users of cookiejar should import "golang.org/x/net/publicsuffix"
cookiejar.WithPublicSuffixList(publicsuffix.List),
)
client := &http.Client{
Jar: jar,
}
if _, err = client.Get(u.String()); err != nil {
log.Fatal(err)
}
fmt.Println("After 1st request:")
for _, cookie := range jar.Cookies(u) {
fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value)
}
if _, err = client.Get(u.String()); err != nil {
log.Fatal(err)
}
fmt.Println("After 2nd request:")
for _, cookie := range jar.Cookies(u) {
fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value)
}
// Output:
// After 1st request:
// Flavor: Chocolate Chip
// After 2nd request:
// Flavor: Oatmeal Raisin
}