Merge pull request #1157 from 0uep/patch-1

Add SameSite in Cookie struct
This commit is contained in:
astaxie
2021-02-22 22:04:37 +08:00
committed by GitHub

View File

@@ -40,44 +40,45 @@ Go uses the `SetCookie` function in the `net/http` package to set cookies:
```
`w` is the response of the request and cookie is a struct. Let's see what it looks like:
```Go
type Cookie struct {
Name string
Value string
Path string
Domain string
Expires time.Time
RawExpires string
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
MaxAge int
Secure bool
HttpOnly bool
Raw string
Unparsed []string // Raw text of unparsed attribute-value pairs
}
type Cookie struct {
Name string
Value string
Path string // optional
Domain string // optional
Expires time.Time // optional
RawExpires string // for reading cookies only
// MaxAge=0 means no 'Max-Age' attribute specified.
// MaxAge<0 means delete cookie now, equivalently 'Max-Age: 0'
// MaxAge>0 means Max-Age attribute present and given in seconds
MaxAge int
Secure bool
HttpOnly bool
SameSite SameSite
Raw string
Unparsed []string // Raw text of unparsed attribute-value pairs
}
```
Here is an example of setting a cookie:
```Go
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
http.SetCookie(w, &cookie)
expiration := time.Now().Add(365 * 24 * time.Hour)
cookie := http.Cookie{Name: "username", Value: "astaxie", Expires: expiration}
http.SetCookie(w, &cookie)
```
## Fetch cookies in Go
The above example shows how to set a cookie. Now let's see how to get a cookie that has been set:
```Go
cookie, _ := r.Cookie("username")
fmt.Fprint(w, cookie)
cookie, _ := r.Cookie("username")
fmt.Fprint(w, cookie)
```
Here is another way to get a cookie:
```Go
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
```
As you can see, it's very convenient to get cookies from requests.