@@ -40,44 +40,45 @@ Go uses the `SetCookie` function in the `net/http` package to set cookies:
40
40
```
41
41
` w ` is the response of the request and cookie is a struct. Let's see what it looks like:
42
42
``` Go
43
- type Cookie struct {
44
- Name string
45
- Value string
46
- Path string
47
- Domain string
48
- Expires time.Time
49
- RawExpires string
50
-
51
- // MaxAge=0 means no 'Max-Age' attribute specified.
52
- // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
53
- // MaxAge>0 means Max-Age attribute present and given in seconds
54
- MaxAge int
55
- Secure bool
56
- HttpOnly bool
57
- Raw string
58
- Unparsed []string // Raw text of unparsed attribute-value pairs
59
- }
43
+ type Cookie struct {
44
+ Name string
45
+ Value string
46
+ Path string // optional
47
+ Domain string // optional
48
+ Expires time.Time // optional
49
+ RawExpires string // for reading cookies only
50
+
51
+ // MaxAge=0 means no 'Max-Age' attribute specified.
52
+ // MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
53
+ // MaxAge>0 means Max-Age attribute present and given in seconds
54
+ MaxAge int
55
+ Secure bool
56
+ HttpOnly bool
57
+ SameSite SameSite
58
+ Raw string
59
+ Unparsed []string // Raw text of unparsed attribute-value pairs
60
+ }
60
61
```
61
62
Here is an example of setting a cookie:
62
63
63
64
``` Go
64
- expiration := time.Now ().Add (365 * 24 * time.Hour )
65
- cookie := http.Cookie {Name: " username" , Value : " astaxie" , Expires : expiration}
66
- http.SetCookie (w, &cookie)
65
+ expiration := time.Now ().Add (365 * 24 * time.Hour )
66
+ cookie := http.Cookie {Name: " username" , Value : " astaxie" , Expires : expiration}
67
+ http.SetCookie (w, &cookie)
67
68
```
68
69
69
70
## Fetch cookies in Go
70
71
71
72
The above example shows how to set a cookie. Now let's see how to get a cookie that has been set:
72
73
``` Go
73
- cookie , _ := r.Cookie (" username" )
74
- fmt.Fprint (w, cookie)
74
+ cookie , _ := r.Cookie (" username" )
75
+ fmt.Fprint (w, cookie)
75
76
```
76
77
Here is another way to get a cookie:
77
78
``` Go
78
- for _ , cookie := range r.Cookies () {
79
- fmt.Fprint (w, cookie.Name )
80
- }
79
+ for _ , cookie := range r.Cookies () {
80
+ fmt.Fprint (w, cookie.Name )
81
+ }
81
82
```
82
83
As you can see, it's very convenient to get cookies from requests.
83
84
0 commit comments