...
1
2
3
4
5 package cookiejar_test
6
7 import (
8 "fmt"
9 "log"
10 "net/http"
11 "net/http/cookiejar"
12 "net/http/httptest"
13 "net/url"
14 )
15
16 func ExampleNew() {
17
18 ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
19 if cookie, err := r.Cookie("Flavor"); err != nil {
20 http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
21 } else {
22 cookie.Value = "Oatmeal Raisin"
23 http.SetCookie(w, cookie)
24 }
25 }))
26 defer ts.Close()
27
28 u, err := url.Parse(ts.URL)
29 if err != nil {
30 log.Fatal(err)
31 }
32
33
34 jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
35 if err != nil {
36 log.Fatal(err)
37 }
38
39 client := &http.Client{
40 Jar: jar,
41 }
42
43 if _, err = client.Get(u.String()); err != nil {
44 log.Fatal(err)
45 }
46
47 fmt.Println("After 1st request:")
48 for _, cookie := range jar.Cookies(u) {
49 fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value)
50 }
51
52 if _, err = client.Get(u.String()); err != nil {
53 log.Fatal(err)
54 }
55
56 fmt.Println("After 2nd request:")
57 for _, cookie := range jar.Cookies(u) {
58 fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value)
59 }
60
61
62
63
64
65 }
66
View as plain text