cookiejar.New, Options, SetCookies, and Cookies
func New(o *Options) (*Jar, error)
type Options struct {
PublicSuffixList PublicSuffixList
}
func (j *Jar) SetCookies(u *url.URL, cookies []*http.Cookie)
func (j *Jar) Cookies(u *url.URL) []*http.CookieWith a nil PublicSuffixList, a cookie for example.test set from foo.example.test is also visible to bar.example.test.
| Parameter | Description |
|---|---|
o | Jar options. nil or a zero Options leaves PublicSuffixList nil. Official documentation calls that useful for testing and not secure. |
u, cookies | The URL of the setting server and the cookie list. Domain, names, and values in this example are fake. |
Returns: New returns *Jar and an error. Cookies returns the cookies the jar would send to that URL.
Errors
error— New can fail if options are unusable; it is nil in this example.
- This is not a SameSite or CORS demonstration, and it is not a browser compliance test.
package main
import (
"fmt"
"net/http"
"net/http/cookiejar"
"net/url"
)
func values(cookies []*http.Cookie) []string {
out := make([]string, 0, len(cookies))
for _, c := range cookies {
out = append(out, c.Name+"="+c.Value)
}
return out
}
func main() {
jar, err := cookiejar.New(nil)
fmt.Println("new", err)
foo, _ := url.Parse("https://foo.example.test/")
bar, _ := url.Parse("https://bar.example.test/")
jar.SetCookies(foo, []*http.Cookie{
{Name: "session", Value: "fake-cookie-not-real", Domain: "example.test", Path: "/"},
})
fmt.Println("foo", values(jar.Cookies(foo)))
fmt.Println("bar", values(jar.Cookies(bar)))
}Expected output
new <nil>
foo [session=fake-cookie-not-real]
bar [session=fake-cookie-not-real]Related: net/url, net/http (client)