From 9b172fe4ab45170937b25571d80d35cb591893e6 Mon Sep 17 00:00:00 2001 From: "Gerasimos (Makis) Maropoulos" Date: Mon, 18 May 2020 18:43:39 +0300 Subject: [PATCH] add a note about sessions transcoder, rel: https://github.com/kataras/iris/issues/1517#issuecomment-630256473 Former-commit-id: 3ac995ea77b4629dc7b0d580b9e36d9e302b96ee --- _examples/sessions/database/badger/main.go | 12 ++++++++++ .../sessions/overview/example/example.go | 24 +++++++++++++++++-- 2 files changed, 34 insertions(+), 2 deletions(-) diff --git a/_examples/sessions/database/badger/main.go b/_examples/sessions/database/badger/main.go index cc245629..d49c1dbb 100644 --- a/_examples/sessions/database/badger/main.go +++ b/_examples/sessions/database/badger/main.go @@ -24,6 +24,18 @@ func main() { defer db.Close() // close and unlock the database if application errored. + // The default transcoder is the JSON one, + // based on the https://golang.org/pkg/encoding/json/#Unmarshal + // you can only retrieve numbers as float64 types: + // * bool, for booleans + // * float64, for numbers + // * string, for strings + // * []interface{}, for arrays + // * map[string]interface{}, for objects. + // If you want to save the data per go-specific types + // you should change the DefaultTranscoder to the GobTranscoder one: + // sessions.DefaultTranscoder = sessions.GobTranscoder{} + sess := sessions.New(sessions.Config{ Cookie: "sessionscookieid", Expires: 1 * time.Minute, // <=0 means unlimited life. Defaults to 0. diff --git a/_examples/sessions/overview/example/example.go b/_examples/sessions/overview/example/example.go index 8f2015d3..f7312c4a 100644 --- a/_examples/sessions/overview/example/example.go +++ b/_examples/sessions/overview/example/example.go @@ -77,9 +77,29 @@ func NewApp(sess *sessions.Sessions) *iris.Application { session := sessions.Get(ctx) // get a specific key, as string, if no found returns just an empty string key := ctx.Params().Get("key") - name := session.GetString(key) + value := session.Get(key) - ctx.Writef("The name on the /set was: %s", name) + ctx.Writef("The [%s:%T] on the /set was: %v", key, value, value) + }) + + app.Get("/set/{type}/{key}/{value}", func(ctx iris.Context) { + session := sessions.Get(ctx) + + key := ctx.Params().Get("key") + var value interface{} + + switch ctx.Params().Get("type") { + case "int": + value = ctx.Params().GetIntDefault("value", 0) + case "float64": + value = ctx.Params().GetFloat64Default("value", 0.0) + default: + value = ctx.Params().Get("value") + } + session.Set(key, value) + + value = session.Get(key) + ctx.Writef("Key: %s, Type: %T, Value: %v", key, value, value) }) app.Get("/delete", func(ctx iris.Context) {