Cookie is a small piece of data sent from a website and stored in the user’s web
browser while the user is browsing. Every time the user loads the website, the browser
sends the cookie back to the server to notify the user’s previous activity.
Cookies were designed to be a reliable mechanism for websites to remember stateful
information (such as items added in the shopping cart in an online store) or to
record the user’s browsing activity (including clicking particular buttons, logging
in, or recording which pages were visited in the past). Cookies can also store
passwords and form content a user has previously entered, such as a credit card
number or an address.

Attribute Optional
Name No
Value No
Path Yes
Domain Yes
Expires Yes
Secure Yes
HttpOnly Yes

Echo uses go standard http.Cookie object to add/retrieve cookies from the context received in the handler function.

  1. func writeCookie(c echo.Context) error {
  2. cookie := new(http.Cookie)
  3. cookie.Name = "username"
  4. cookie.Value = "jon"
  5. cookie.Expires = time.Now().Add(24 * time.Hour)
  6. c.SetCookie(cookie)
  7. return c.String(http.StatusOK, "write a cookie")
  8. }
  • Cookie is created using new(http.Cookie).
  • Attributes for the cookie are set assigning to the http.Cookie instance public attributes.
  • Finally c.SetCookie(cookies) adds a Set-Cookie header in HTTP response.
  1. func readCookie(c echo.Context) error {
  2. cookie, err := c.Cookie("username")
  3. if err != nil {
  4. return err
  5. }
  6. fmt.Println(cookie.Name)
  7. fmt.Println(cookie.Value)
  8. return c.String(http.StatusOK, "read a cookie")
  9. }
  • Cookie is read by name using c.Cookie("username") from the HTTP request.
  • Cookie attributes are accessed using Getter function.

Read all Cookies

  1. func readAllCookies(c echo.Context) error {
  2. for _, cookie := range c.Cookies() {
  3. fmt.Println(cookie.Name)
  4. fmt.Println(cookie.Value)
  5. }
  6. return c.String(http.StatusOK, "read all cookie")
  7. }