Cookie

Cookie example

Basic Usage

  • GetCookie(key string)
  • SetCookie(name string, value string, others ...interface{})

Example:

  1. type MainController struct {
  2. web.Controller
  3. }
  4. func (ctrl *MainController) PutCookie() {
  5. // put something into cookie,set Expires time
  6. ctrl.Ctx.SetCookie("name", "web cookie", 10)
  7. // web-example/views/hello_world.html
  8. ctrl.TplName = "hello_world.html"
  9. ctrl.Data["name"] = "PutCookie"
  10. _ = ctrl.Render()
  11. }
  12. func (ctrl *MainController) ReadCookie() {
  13. // web-example/views/hello_world.html
  14. ctrl.TplName = "hello_world.html"
  15. ctrl.Data["name"] = ctrl.Ctx.GetCookie("name")
  16. // don't forget this
  17. _ = ctrl.Render()
  18. }

others means:

  • others[0]: maxAge, means Expires and Max-Age
  • others[1]: Path, string, the default value is /
  • others[2]: Domain, string
  • others[3]: Secure, bool
  • others[4]: HttpOnly, bool
  • others[5]: SameSite, string

Encryption

Beego provides two methods to assist with cookie encryption, it uses sha256 as the encryption algorithm and Secret as the encryption key:

  • GetSecureCookie(Secret, key string) (string, bool)
  • SetSecureCookie(Secret, name, value string, others ...interface{})
  1. type MainController struct {
  2. web.Controller
  3. }
  4. func (ctrl *MainController) PutSecureCookie() {
  5. // put something into cookie,set Expires time
  6. ctrl.Ctx.SetSecureCookie("my-secret", "name", "web cookie")
  7. // web-example/views/hello_world.html
  8. ctrl.TplName = "hello_world.html"
  9. ctrl.Data["name"] = "PutCookie"
  10. _ = ctrl.Render()
  11. }
  12. func (ctrl *MainController) ReadSecureCookie() {
  13. // web-example/views/hello_world.html
  14. ctrl.TplName = "hello_world.html"
  15. ctrl.Data["name"], _ = ctrl.Ctx.GetSecureCookie("my-secret", "name")
  16. // don't forget this
  17. _ = ctrl.Render()
  18. }

Please refer to above section to learn others.