NewApp returns a new application for showcasing the sessions feature.
(sess *sessions.Sessions)
| 15 | |
| 16 | // NewApp returns a new application for showcasing the sessions feature. |
| 17 | func NewApp(sess *sessions.Sessions) *iris.Application { |
| 18 | app := iris.New() |
| 19 | app.Use(sess.Handler()) // register the session manager on a group of routes or the root app. |
| 20 | |
| 21 | app.Get("/", func(ctx iris.Context) { |
| 22 | session := sessions.Get(ctx) // same as sess.Start(ctx, cookieOptions...) |
| 23 | if session.Len() == 0 { |
| 24 | ctx.HTML(`no session values stored yet. Navigate to: <a href="/set">set page</a>`) |
| 25 | return |
| 26 | } |
| 27 | |
| 28 | ctx.HTML("<ul>") |
| 29 | session.Visit(func(key string, value interface{}) { |
| 30 | ctx.HTML("<li> %s = %v </li>", key, value) |
| 31 | }) |
| 32 | |
| 33 | ctx.HTML("</ul>") |
| 34 | }) |
| 35 | |
| 36 | // set session values. |
| 37 | app.Get("/set", func(ctx iris.Context) { |
| 38 | session := sessions.Get(ctx) |
| 39 | isNew := session.IsNew() |
| 40 | |
| 41 | session.Set("username", "iris") |
| 42 | |
| 43 | ctx.Writef("All ok session set to: %s [isNew=%t]", session.GetString("username"), isNew) |
| 44 | }) |
| 45 | |
| 46 | app.Get("/get", func(ctx iris.Context) { |
| 47 | session := sessions.Get(ctx) |
| 48 | |
| 49 | // get a specific value, as string, |
| 50 | // if not found then it returns just an empty string. |
| 51 | name := session.GetString("username") |
| 52 | |
| 53 | ctx.Writef("The username on the /set was: %s", name) |
| 54 | }) |
| 55 | |
| 56 | app.Get("/set-struct", func(ctx iris.Context) { |
| 57 | session := sessions.Get(ctx) |
| 58 | session.Set("struct", BusinessModel{Name: "John Doe"}) |
| 59 | |
| 60 | ctx.WriteString("All ok session value of the 'struct' was set.") |
| 61 | }) |
| 62 | |
| 63 | app.Get("/get-struct", func(ctx iris.Context) { |
| 64 | session := sessions.Get(ctx) |
| 65 | var v BusinessModel |
| 66 | if err := session.Decode("struct", &v); err != nil { |
| 67 | ctx.StopWithError(iris.StatusInternalServerError, err) |
| 68 | return |
| 69 | } |
| 70 | ctx.Writef("Session value of the 'struct' is: %#+v", v) |
| 71 | }) |
| 72 | |
| 73 | app.Get("/set/{key}/{value}", func(ctx iris.Context) { |
| 74 | session := sessions.Get(ctx) |
no test coverage detected
searching dependent graphs…