-
-
Notifications
You must be signed in to change notification settings - Fork 52
/
cookies_example_test.go
62 lines (57 loc) · 1.42 KB
/
cookies_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
package requests_test
import (
"context"
"fmt"
"net/http"
"net/url"
"github.com/carlmjohnson/requests"
)
func ExampleNewCookieJar() {
// Create a client that preserve cookies between requests
myClient := *http.DefaultClient
myClient.Jar = requests.NewCookieJar()
// Use the client to make a request
err := requests.
URL("http://httpbin.org/cookies/set/chocolate/chip").
Client(&myClient).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to httpbin.org:", err)
}
// Now check that cookies we got
for _, cookie := range myClient.Jar.Cookies(&url.URL{
Scheme: "http",
Host: "httpbin.org",
}) {
fmt.Println(cookie)
}
// And we'll see that they're reused on subsequent requests
var cookies struct {
Cookies map[string]string
}
err = requests.
URL("http://httpbin.org/cookies").
Client(&myClient).
ToJSON(&cookies).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to httpbin.org:", err)
}
fmt.Println(cookies)
// And we can manually add our own cookie values
// without overriding existing ones
err = requests.
URL("http://httpbin.org/cookies").
Client(&myClient).
Cookie("oatmeal", "raisin").
ToJSON(&cookies).
Fetch(context.Background())
if err != nil {
fmt.Println("could not connect to httpbin.org:", err)
}
fmt.Println(cookies)
// Output:
// chocolate=chip
// {map[chocolate:chip]}
// {map[chocolate:chip oatmeal:raisin]}
}