diff --git a/_example/gorm/main.go b/_example/gorm/main.go new file mode 100644 index 0000000..5480395 --- /dev/null +++ b/_example/gorm/main.go @@ -0,0 +1,36 @@ +package main + +import ( + "github.com/gin-contrib/sessions" + gormsessions "github.com/gin-contrib/sessions/gorm" + "github.com/gin-gonic/gin" + "gorm.io/driver/sqlite" + "gorm.io/gorm" +) + +func main() { + db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{}) + if err != nil { + panic(err) + } + store := gormsessions.NewStore(db, true, []byte("secret")) + + r := gin.Default() + r.Use(sessions.Sessions("mysession", store)) + + r.GET("/incr", func(c *gin.Context) { + session := sessions.Default(c) + var count int + v := session.Get("count") + if v == nil { + count = 0 + } else { + count = v.(int) + count++ + } + session.Set("count", count) + session.Save() + c.JSON(200, gin.H{"count": count}) + }) + r.Run(":8000") +}