Cookie 处理

这部分的例子在Cookie example

Beego 通过Context直接封装了对普通 Cookie 的处理方法,可以直接使用:

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

例子:

  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参数含义依次是:

  • 第一个代表 maxAge,Beego 使用这个值计算ExpiresMax-Age两个值
  • 第二个代表Path,字符串类型,默认值是/
  • 第三个代表Domain,字符串类型
  • 第四个代表Secure,布尔类型
  • 第五个代表HttpOnly,布尔类型
  • 第六个代表SameSite,字符串类型

Beego 提供了两个方法用于辅助 Cookie 加密处理,它采用了sha256来作为加密算法,下面Secret则是加密的密钥:

  • GetSecureCookie(Secret, key string) (string, bool):用于从 Cookie 中读取数据
  • SetSecureCookie(Secret, name, value string, others ...interface{}):用于写入数据到 Cookie。
  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. }

others参数和普通 Cookie 一样。