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.
import "github.com/kataras/iris/v12"
func main() {
app := iris.Default()
app.Get("/cookie", func(ctx iris.Context) {
value := ctx.GetCookie("my_cookie")
if value == "" {
value = "NotSet"
ctx.SetCookieKV("my_cookie", value)
// Alternatively: ctx.SetCookie(&http.Cookie{...})
ctx.SetCookie("", "test", 3600, "/", "localhost", false, true)
}
ctx.Writef("Cookie value: %s \n", cookie)
})
app.Listen(":8080")
}
If you want to set custom the path:
ctx.SetCookieKV(name, value, iris.CookiePath("/custom/path/cookie/will/be/stored"))
If you want to be visible only to current request path:
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:
func setCookieOptions(ctx iris.Context) {
ctx.AddCookieOptions(iris.CookieHTTPOnly(true), iris.CookieExpires(1*time.Hour))
ctx.Next()
}