Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add SameSite in Cookie struct #1157

Merged
merged 1 commit into from
Feb 22, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 26 additions & 25 deletions en/06.1.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down