Set and get a cookie

Secure cookies, encoding and decoding, sessions (and sessions scaling), flash messages and more can be found at the _examples/cookies and _examples/sessions directories respectfully.

  1. import "github.com/kataras/iris/v12"
  2. func main() {
  3. app := iris.Default()
  4. app.Get("/cookie", func(ctx iris.Context) {
  5. value := ctx.GetCookie("my_cookie")
  6. if value == "" {
  7. value = "NotSet"
  8. ctx.SetCookieKV("my_cookie", value)
  9. // Alternatively: ctx.SetCookie(&http.Cookie{...})
  10. ctx.SetCookie("", "test", 3600, "/", "localhost", false, true)
  11. }
  12. ctx.Writef("Cookie value: %s \n", cookie)
  13. })
  14. app.Listen(":8080")
  15. }

If you want to set custom the path:

  1. ctx.SetCookieKV(name, value, iris.CookiePath("/custom/path/cookie/will/be/stored"))

If you want to be visible only to current request path:

  1. ctx.SetCookieKV(name, value, iris.CookieCleanPath /* or iris.CookiePath("") */)

More:

  • iris.CookieAllowReclaim
  • iris.CookieAllowSubdomains
  • iris.CookieSecure
  • iris.CookieHTTPOnly
  • iris.CookieSameSite
  • iris.CookiePath
  • iris.CookieCleanPath
  • iris.CookieExpires
  • iris.CookieEncoding

You can add cookie options for the whole request in a middleware too:

  1. func setCookieOptions(ctx iris.Context) {
  2. ctx.AddCookieOptions(iris.CookieHTTPOnly(true), iris.CookieExpires(1*time.Hour))
  3. ctx.Next()
  4. }