Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/shaopson/sessions
A simple gin session middleware, support memory, file, redis, databaes store backend.
https://github.com/shaopson/sessions
gin session
Last synced: 14 days ago
JSON representation
A simple gin session middleware, support memory, file, redis, databaes store backend.
- Host: GitHub
- URL: https://github.com/shaopson/sessions
- Owner: shaopson
- License: mit
- Created: 2022-08-16T14:34:36.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2023-04-06T02:15:27.000Z (over 1 year ago)
- Last Synced: 2024-10-29T10:48:10.244Z (17 days ago)
- Topics: gin, session
- Language: Go
- Homepage:
- Size: 30.3 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# gin-session
A simple gin session middleware, support memory, file, redis, database store backend.## Install
```
go get github.com/dev-shao/sessions
```
## Quick start```go
package mainimport (
"github.com/dev-shao/sessions"
"github.com/gin-gonic/gin"
)func main() {
//gin router
router := gin.Default()
//file store
store := sessions.NewFileStore("./")
//use middleware
router.Use(sessions.Middleware(store))
router.GET("/test", func(context *gin.Context) {
//get instance with context
session, _ := sessions.Get(context)
//set
session.Set("key", "hello")
//get
value := session.Get("key")
//delete
session.Delete("key")
context.String(200, value.(string))
})
router.Run()
}
```## Store Backend
### FileStore
```go
//session file store path
path := "./"
store := sessions.NewFileStore(path)
```### RedisStore
```go
package mainimport (
"github.com/dev-shao/sessions"
"github.com/go-redis/redis"
)func main() {
opt := &redis.Options{
Network: "tcp",
Addr: "127.0.0.1:6379",
DB: 0,
}
client := redis.NewClient(opt)
store := sessions.NewRedisStore(client)
middleware := sessions.Middleware(store)
}
```### DBStore
#### sqlite3
install sqlite3 driver```shell
go get github.com/mattn/go-sqlite
``````go
package mainimport (
"database/sql"
"github.com/dev-shao/sessions"
_ "github.com/mattn/go-sqlite3"
)func main() {
db, err := sql.Open("sqlite3", "./test.db")
if err != nil {
panic(err)
}
store := sessions.NewDBStore("session", db)
middleware := sessions.Middleware(store)
...
}
```
#### mysqlinstall mysql driver
```shell
go get github.com/go-sql-driver/mysql
``````go
package mainimport (
"database/sql"
"github.com/dev-shao/sessions"
_ "github.com/go-sql-driver/mysql"
)func main() {
dsn := "user:pass@tcp(127.0.0.1:3306)/dbname?charset=utf8mb4&parseTime=True&loc=Local"
db, err := sql.Open("mysql", dsn)
if err != nil {
panic(err)
}
store := sessions.NewDBStore("session", db)
middleware := sessions.Middleware(store)
...
}
```### MemoryStore
only used in test or development environment
```go
middleware := sessions.Middleware(sessions.NewMemoryStore())
```