net/http/cookiejar
Package cookiejar implements an in-memory RFC 6265-compliant http.CookieJar.
Index
Functions
func New
1func New(o *Options) (*Jar, error)
New returns a new cookie jar. A nil *Options is equivalent to a zero Options.
Example
1ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2 if cookie, err := r.Cookie("Flavor"); err != nil {
3 http.SetCookie(w, &http.Cookie{Name: "Flavor", Value: "Chocolate Chip"})
4 } else {
5 cookie.Value = "Oatmeal Raisin"
6 http.SetCookie(w, cookie)
7 }
8}))
9defer ts.Close()
10
11u, err := url.Parse(ts.URL)
12if err != nil {
13 log.Fatal(err)
14}
15
16jar, err := cookiejar.New(&cookiejar.Options{PublicSuffixList: publicsuffix.List})
17if err != nil {
18 log.Fatal(err)
19}
20
21client := &http.Client{
22 Jar: jar,
23}
24
25if _, err = client.Get(u.String()); err != nil {
26 log.Fatal(err)
27}
28
29fmt.Println("After 1st request:")
30for _, cookie := range jar.Cookies(u) {
31 fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value)
32}
33
34if _, err = client.Get(u.String()); err != nil {
35 log.Fatal(err)
36}
37
38fmt.Println("After 2nd request:")
39for _, cookie := range jar.Cookies(u) {
40 fmt.Printf(" %s: %s\n", cookie.Name, cookie.Value)
41}
Output
After 1st request: Flavor: Chocolate Chip After 2nd request: Flavor: Oatmeal Raisin
Types
type Options
1type Options struct {
2 // PublicSuffixList is the public suffix list that determines whether
3 // an HTTP server can set a cookie for a domain.
4 //
5 // A nil value is valid and may be useful for testing but it is not
6 // secure: it means that the HTTP server for foo.co.uk can set a cookie
7 // for bar.co.uk.
8 PublicSuffixList PublicSuffixList
9}
Options are the options for creating a new Jar.
type PublicSuffixList
1type PublicSuffixList interface {
2 // PublicSuffix returns the public suffix of domain.
3 //
4 // TODO: specify which of the caller and callee is responsible for IP
5 // addresses, for leading and trailing dots, for case sensitivity, and
6 // for IDN/Punycode.
7 PublicSuffix(domain string) string
8
9 // String returns a description of the source of this public suffix
10 // list. The description will typically contain something like a time
11 // stamp or version number.
12 String() string
13}
PublicSuffixList provides the public suffix of a domain. For example:
- the public suffix of “example.com” is “com”,
- the public suffix of “foo1.foo2.foo3.co.uk” is “co.uk”, and
- the public suffix of “bar.pvt.k12.ma.us” is “pvt.k12.ma.us”.
Implementations of PublicSuffixList must be safe for concurrent use by multiple goroutines.
An implementation that always returns "" is valid and may be useful for testing but it is not secure: it means that the HTTP server for foo.com can set a cookie for bar.com.
A public suffix list implementation is in the package golang.org/x/net/publicsuffix.