-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
94 lines (78 loc) · 2.23 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package main
import (
"fmt"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/session"
"github.com/gofiber/storage/coherence"
"log"
"strings"
"time"
)
var store *session.Store
func main() {
// create new coherence session store using defaults of localhost:1408
storage, err := coherence.New()
if err != nil {
log.Fatal("unable to connect to Coherence ", err)
}
defer storage.Close()
//storage.Conn().AddSessionLifecycleListener(coh.NewSessionLifecycleListener().
// OnAny(func(e coh.SessionLifecycleEvent) {
// fmt.Printf("**EVENT=%s: source=%v\n", e.Type(), e.Source())
// if e.Type() == coh.Disconnected {
// os.Exit(1)
// }
// }))
// initialize the gofiber session store using the Coherence storage driver
store = session.New(session.Config{
Storage: storage,
Expiration: time.Duration(120) * time.Second,
})
app := fiber.New()
app.Get("/", func(c *fiber.Ctx) error {
// retrieve the session
sess, err1 := store.Get(c)
if err1 != nil {
log.Println(err1)
return c.Status(500).SendString(err1.Error())
}
if sess.Fresh() {
// new session
sess.Set("accessCount", 1)
sess.Set("firstAccess", time.Now().Format(time.ANSIC))
} else {
// increment the number of times we have hit this endpoint
count := sess.Get("accessCount").(int)
count++
sess.Set("accessCount", count)
sess.Set("lastAccess", time.Now().Format(time.ANSIC))
}
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Session: %s, new=%v\nSession values:\n", sess.ID(), sess.Fresh()))
for _, k := range sess.Keys() {
sb.WriteString(fmt.Sprintf(" %s=%v\n", k, sess.Get(k)))
}
if err1 = sess.Save(); err1 != nil {
log.Println(err1)
return c.Status(500).SendString(err1.Error())
}
return c.SendString(sb.String())
})
app.Get("/destroy", func(c *fiber.Ctx) error {
// retrieve the session
sess, err1 := store.Get(c)
if err1 != nil {
log.Println(err1)
return c.Status(500).SendString(err1.Error())
}
id := sess.ID()
// remove the session
err1 = sess.Destroy()
if err1 != nil {
log.Println(err1)
return c.Status(500).SendString(err1.Error())
}
return c.Status(200).SendString(fmt.Sprintf("session %v destroyed", id))
})
panic(app.Listen("127.0.0.1:2000"))
}