Sessions
Create a main.go file and copy-paste the following code snippets:
1
package main
2
3
import (
4
"fmt"
5
"time"
6
7
"github.com/kataras/iris/v12"
8
"github.com/kataras/iris/v12/mvc"
9
"github.com/kataras/iris/v12/sessions"
10
)
11
12
func main() {
13
app := iris.New()
14
15
// Configure sessions manager as we used to.
16
sess := sessions.New(sessions.Config{Cookie: "mysession_cookie_name"})
17
app.Use(sess.Handler())
18
19
visitApp := mvc.New(app)
20
visitApp.Register(time.Now())
21
visitApp.Handle(new(VisitController))
22
23
app.Listen(":8080")
24
}
Copied!

Controller

    The VisitController.Session is automatically binded to the current sessions.Session.
    The VisitController.StartTime is statically set to the server's start time with .Register(time.Now()) above.
1
type VisitController struct {
2
Session *sessions.Session
3
4
StartTime time.Time
5
}
6
7
func (c *VisitController) Get() string {
8
// it increments a "visits" value of integer by one,
9
// if the entry with key 'visits' doesn't exist
10
// it will create it for you.
11
visits := c.Session.Increment("visits", 1)
12
// write the current, updated visits.
13
since := time.Now().Sub(c.StartTime).Seconds()
14
return fmt.Sprintf("%d visit(s) from my current session in %0.1f seconds of server's up-time",
15
visits, since)
16
}
Copied!

Run

Open a terminal session and execute:
1
$ go run main.go
Copied!
    1.
    Prepare a client, e.g. your browser
    2.
    navigate to http://localhost:8080
    3.
    refresh the page some times
    4.
    close the browser
    5.
    re-open the browser (if it wasn't in private mode) and re-play 2.
Last modified 1yr ago
Export as PDF
Copy link