2018-06-02 15:35:18 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
// developers can use any library to add a custom cookie encoder/decoder.
|
|
|
|
// At this example we use the gorilla's securecookie package:
|
|
|
|
// $ go get github.com/gorilla/securecookie
|
|
|
|
// $ go run main.go
|
|
|
|
|
|
|
|
import (
|
2019-10-25 00:27:02 +02:00
|
|
|
"github.com/kataras/iris/v12"
|
2018-06-02 15:35:18 +02:00
|
|
|
|
|
|
|
"github.com/gorilla/securecookie"
|
|
|
|
)
|
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
func main() {
|
|
|
|
app := newApp()
|
|
|
|
// http://localhost:8080/cookies/name/value
|
|
|
|
// http://localhost:8080/cookies/name
|
|
|
|
// http://localhost:8080/cookies/remove/name
|
|
|
|
app.Listen(":8080")
|
|
|
|
}
|
2018-06-02 15:35:18 +02:00
|
|
|
|
|
|
|
func newApp() *iris.Application {
|
|
|
|
app := iris.New()
|
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
r := app.Party("/cookies")
|
|
|
|
{
|
|
|
|
r.Use(useSecureCookies())
|
|
|
|
|
|
|
|
// Set A Cookie.
|
|
|
|
r.Get("/{name}/{value}", func(ctx iris.Context) {
|
|
|
|
name := ctx.Params().Get("name")
|
|
|
|
value := ctx.Params().Get("value")
|
2018-06-02 15:35:18 +02:00
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
ctx.SetCookieKV(name, value)
|
2018-06-02 15:35:18 +02:00
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
ctx.Writef("cookie added: %s = %s", name, value)
|
|
|
|
})
|
2018-06-02 15:35:18 +02:00
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
// Retrieve A Cookie.
|
|
|
|
r.Get("/{name}", func(ctx iris.Context) {
|
|
|
|
name := ctx.Params().Get("name")
|
2018-06-02 15:35:18 +02:00
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
value := ctx.GetCookie(name)
|
2018-06-02 15:35:18 +02:00
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
ctx.WriteString(value)
|
|
|
|
})
|
2018-06-02 15:35:18 +02:00
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
r.Get("/remove/{name}", func(ctx iris.Context) {
|
|
|
|
name := ctx.Params().Get("name")
|
2018-06-02 15:35:18 +02:00
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
ctx.RemoveCookie(name)
|
2018-06-02 15:35:18 +02:00
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
ctx.Writef("cookie %s removed", name)
|
|
|
|
})
|
|
|
|
}
|
2018-06-02 15:35:18 +02:00
|
|
|
|
|
|
|
return app
|
|
|
|
}
|
|
|
|
|
2020-05-09 13:04:51 +02:00
|
|
|
func useSecureCookies() iris.Handler {
|
|
|
|
var (
|
|
|
|
hashKey = securecookie.GenerateRandomKey(64)
|
|
|
|
blockKey = securecookie.GenerateRandomKey(32)
|
|
|
|
|
|
|
|
s = securecookie.New(hashKey, blockKey)
|
|
|
|
)
|
|
|
|
|
|
|
|
return func(ctx iris.Context) {
|
|
|
|
ctx.AddCookieOptions(iris.CookieEncoding(s))
|
|
|
|
ctx.Next()
|
|
|
|
}
|
2018-06-02 15:35:18 +02:00
|
|
|
}
|