Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add mysql #173

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions _example/mysql/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package main

import (
"fmt"
"github.com/gin-contrib/sessions"
"github.com/gin-contrib/sessions/mysql"
"github.com/gin-gonic/gin"
"time"
)

func main() {
r := gin.Default()

userStr := ""
passStr := ""
ipStr := ""
databaseStr := ""
portStr := ""
connStr := fmt.Sprintf("%s:%s@(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local",userStr,passStr,ipStr,portStr,databaseStr)
store,err := mysql.NewStore(connStr,"sessionstore", "/", 3600, []byte("kukunet"))
if err != nil {
fmt.Println("Error connecting to MySQL: ", err)
}

//add session
r.Use(sessions.Sessions("mySession", &store))
defer store.Close()
defer store.StopCleanup(store.Cleanup(time.Minute * 5))

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")
}
41 changes: 41 additions & 0 deletions mysql/mysql.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package mysql

import (
"github.com/gin-contrib/sessions"
"github.com/srinathgs/mysqlstore"
"time"
)

type SessionStore interface {
sessions.Store
}

type store struct {
*mysqlstore.MySQLStore
}

func NewStore(endpoint string, tableName string, path string, maxAge int, keyPairs ...[]byte) (store, error) {
p, err := mysqlstore.NewMySQLStore(endpoint, tableName, path, maxAge, keyPairs...)
if err != nil {
return store{},err
}

return store{p}, nil
}

func (s *store) Options(options sessions.Options) {
s.MySQLStore.Options = options.ToGorillaOptions()
}

func (s *store) Close() {
s.MySQLStore.Close()
}

func (s *store) Cleanup(interval time.Duration) (chan<- struct{}, <-chan struct{}){
n,m := s.MySQLStore.Cleanup(interval)
return n, m
}

func (s *store) StopCleanup(quit chan<- struct{}, done <-chan struct{}) {
s.MySQLStore.StopCleanup(quit,done)
}