Cookies

Cookie is a small piece of data sent from a website server and stored in the user’s webbrowser while browsing. Every time the user loads the website, the browsersends the cookies back to the server to notify the server of user’s latest activity.Cookies were designed to be a reliable mechanism for websites to remember statefulinformation (e.g. items added to the shopping cart in an online store) or torecord the user’s browsing activity (such as clicking particular buttons, loggingin, or user previously visited pages of the website). Cookies can also store form content a user has previously entered, such as username, gender, age, address, etc.

AttributeOptional
NameNo
ValueNo
PathYes
DomainYes
ExpiresYes
SecureYes
HttpOnlyYes

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(cookie) 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 the 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 the cookies")
  7. }