Cookies
Since HTTP is a stateless protocol, the server cannot record the browsing state, which means the server cannot distinguish whether multiple requests are sent by the same client. This design seriously hinders web program design. For example, when we shop online, buying a pair of pants and then buying a phone, without other auxiliary means, the server cannot know what the user actually bought. Cookie is one of the solutions.
Cookies are designed to be a reliable mechanism for remembering website state and information. Every time we load a website, the browser sends cookies back to the server to notify the server of the user's latest activity, and the server responds differently based on this.
We use Go's standard library, and through the Context, we can receive, set, and add cookie objects in handler functions.
Cookie Attributes
| Attribute | Required |
|---|---|
| Name | Yes |
| Value | Yes |
| Path | No |
| Domain | No |
| Expires | No |
| Secure | No |
| HttpOnly | No |
Creating Cookies
func writeCookie(c slim.Context) error {
cookie := new(http.Cookie)
cookie.Name = "username"
cookie.Value = "jon"
cookie.Expires = time.Now().Add(24 * time.Hour)
c.SetCookie(cookie)
return c.String(http.StatusOK, "write a cookie")
}
From the above code, we can see the steps to add a cookie:
- Use Go's standard library to create a cookie with the code
new(http.Cookie); - Then set the relevant properties of the http.Cookie instance:
Name,Path,Expires; - Finally, use the method
c.SetCookie(cookie)to add it to the HTTP response header Set-Cookie.
Reading Cookies
In our route handler function, we can quickly get the cookie named username set earlier with the result being an http.Cookie struct through the context c.Cookie("username").
func readCookie(c slim.Context) error {
cookie, err := c.Cookie("username")
if err != nil {
return err
}
fmt.Println(cookie.Name)
fmt.Println(cookie.Value)
return c.String(http.StatusOK, "read a cookie")
}
All Cookies
We can get all cookies that have not expired through the context's Context#Cookies method:
func readAllCookies(c slim.Context) error {
for _, cookie := range c.Cookies() {
fmt.Println(cookie.Name)
fmt.Println(cookie.Value)
}
return c.String(http.StatusOK, "read all the cookies")
}