...
1 package main
2
3 import (
4 "context"
5 "github.com/gin-contrib/sessions"
6 "github.com/gin-contrib/sessions/mongo/mongodriver"
7 "github.com/gin-gonic/gin"
8 "go.mongodb.org/mongo-driver/mongo"
9 "go.mongodb.org/mongo-driver/mongo/options"
10 )
11
12 func main() {
13 r := gin.Default()
14 mongoOptions := options.Client().ApplyURI("mongodb://localhost:27017")
15 client, err := mongo.NewClient(mongoOptions)
16 if err != nil {
17
18 }
19
20 if err := client.Connect(context.Background()); err != nil {
21
22 }
23
24 c := client.Database("test").Collection("sessions")
25 store := mongodriver.NewStore(c, 3600, true, []byte("secret"))
26 r.Use(sessions.Sessions("mysession", store))
27
28 r.GET("/incr", func(c *gin.Context) {
29 session := sessions.Default(c)
30 var count int
31 v := session.Get("count")
32 if v == nil {
33 count = 0
34 } else {
35 count = v.(int)
36 count++
37 }
38 session.Set("count", count)
39 session.Save()
40 c.JSON(200, gin.H{"count": count})
41 })
42 r.Run(":8000")
43 }
44
View as plain text