initial
This commit is contained in:
65
redis/redis.go
Normal file
65
redis/redis.go
Normal file
@ -0,0 +1,65 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"code.icod.de/gin-session/sessions"
|
||||
"code.icod.de/gin-session/sessions/redisstore"
|
||||
"github.com/go-redis/redis/v8"
|
||||
)
|
||||
|
||||
type Store interface {
|
||||
sessions.Store
|
||||
}
|
||||
|
||||
// NewStore creates a new store with address="localhost:6379" and prefix="session:"
|
||||
func NewStore(address string, prefix string) (Store, error) {
|
||||
if address == "" {
|
||||
address = "localhost:6379"
|
||||
}
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: address,
|
||||
})
|
||||
s, err := redisstore.NewRedisStore(context.Background(), client)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if prefix == "" {
|
||||
prefix = "session:"
|
||||
}
|
||||
s.KeyPrefix(prefix)
|
||||
return &store{s}, nil
|
||||
}
|
||||
|
||||
type store struct {
|
||||
*redisstore.RedisStore
|
||||
}
|
||||
|
||||
// GetRedisStore get the actual woking store.
|
||||
// Ref: https://godoc.org/github.com/boj/redistore#RediStore
|
||||
func GetRedisStore(s Store) (err error, rediStore *redisstore.RedisStore) {
|
||||
realStore, ok := s.(*store)
|
||||
if !ok {
|
||||
err = errors.New("unable to get the redis store: Store isn't *store")
|
||||
return
|
||||
}
|
||||
|
||||
rediStore = realStore.RedisStore
|
||||
return
|
||||
}
|
||||
|
||||
// SetKeyPrefix sets the key prefix in the redis database.
|
||||
func SetKeyPrefix(s Store, prefix string) error {
|
||||
err, rediStore := GetRedisStore(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
rediStore.KeyPrefix(prefix)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *store) Options(options sessions.Options) {
|
||||
c.RedisStore.Options = *options.ToGorillaOptions()
|
||||
}
|
Reference in New Issue
Block a user