2017-08-18 16:09:18 +02:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
2017-10-12 20:24:11 +02:00
|
|
|
"fmt"
|
2017-08-18 16:09:18 +02:00
|
|
|
"time"
|
|
|
|
|
2019-10-25 00:27:02 +02:00
|
|
|
"github.com/kataras/iris/v12"
|
|
|
|
"github.com/kataras/iris/v12/mvc"
|
|
|
|
"github.com/kataras/iris/v12/sessions"
|
2017-08-18 16:09:18 +02:00
|
|
|
)
|
|
|
|
|
2017-10-12 20:24:11 +02:00
|
|
|
// VisitController handles the root route.
|
2017-08-18 16:09:18 +02:00
|
|
|
type VisitController struct {
|
2020-02-29 13:18:15 +01:00
|
|
|
// the current request session, automatically binded.
|
2017-10-12 20:24:11 +02:00
|
|
|
Session *sessions.Session
|
2017-08-18 16:09:18 +02:00
|
|
|
|
2020-02-29 13:18:15 +01:00
|
|
|
// A time.time which is binded from the MVC application manually.
|
2017-08-18 16:09:18 +02:00
|
|
|
StartTime time.Time
|
|
|
|
}
|
|
|
|
|
2020-02-29 13:18:15 +01:00
|
|
|
// Get handles index
|
2017-10-12 20:24:11 +02:00
|
|
|
// Method: GET
|
|
|
|
// Path: http://localhost:8080
|
|
|
|
func (c *VisitController) Get() string {
|
2017-12-16 20:27:20 +01:00
|
|
|
// it increments a "visits" value of integer by one,
|
|
|
|
// if the entry with key 'visits' doesn't exist it will create it for you.
|
|
|
|
visits := c.Session.Increment("visits", 1)
|
2017-10-12 20:24:11 +02:00
|
|
|
// write the current, updated visits.
|
|
|
|
since := time.Now().Sub(c.StartTime).Seconds()
|
2018-07-23 14:58:55 +02:00
|
|
|
return fmt.Sprintf("%d visit(s) from my current session in %0.1f seconds of server's up-time",
|
2017-10-12 20:24:11 +02:00
|
|
|
visits, since)
|
2017-08-18 16:09:18 +02:00
|
|
|
}
|
|
|
|
|
2017-12-16 20:27:20 +01:00
|
|
|
func newApp() *iris.Application {
|
2017-08-18 16:09:18 +02:00
|
|
|
app := iris.New()
|
2020-06-23 23:13:31 +02:00
|
|
|
// Configure sessions manager as we used to.
|
2017-12-16 20:27:20 +01:00
|
|
|
sess := sessions.New(sessions.Config{Cookie: "mysession_cookie_name"})
|
2020-02-29 13:18:15 +01:00
|
|
|
app.Use(sess.Handler())
|
2017-08-18 16:09:18 +02:00
|
|
|
|
2020-02-29 13:18:15 +01:00
|
|
|
visitApp := mvc.New(app)
|
2020-06-23 23:13:31 +02:00
|
|
|
visitApp.Register(time.Now())
|
|
|
|
// The `VisitController.Session` is automatically binded to the current `sessions.Session`.
|
|
|
|
|
2017-12-27 03:15:41 +01:00
|
|
|
visitApp.Handle(new(VisitController))
|
2017-12-16 20:27:20 +01:00
|
|
|
|
|
|
|
return app
|
|
|
|
}
|
|
|
|
|
|
|
|
func main() {
|
|
|
|
app := newApp()
|
2017-08-18 16:09:18 +02:00
|
|
|
|
2020-06-23 23:13:31 +02:00
|
|
|
// 1. Prepare a client, e.g. your browser
|
2017-08-18 16:09:18 +02:00
|
|
|
// 2. navigate to http://localhost:8080
|
|
|
|
// 3. refresh the page some times
|
|
|
|
// 4. close the browser
|
2019-02-19 21:49:16 +01:00
|
|
|
// 5. re-open the browser (if it wasn't in private mode) and re-play 2.
|
2020-03-05 21:41:27 +01:00
|
|
|
app.Listen(":8080")
|
2017-08-18 16:09:18 +02:00
|
|
|
}
|