feat: adding redis to save sessions

This commit is contained in:
efim
2023-10-29 11:44:28 +00:00
parent bde58a0eab
commit 0591a28f8a
8 changed files with 87 additions and 15 deletions

View File

@@ -1,27 +1,69 @@
package sessions
import (
"context"
"fmt"
"log"
"math/rand"
"github.com/redis/go-redis/v9"
)
type SessionData struct {
sessionId int64
roomId int64
personId int64
SessionId int64 `redis:"session_id"`
RoomId int64 `redis:"room_id"`
PersonId int64 `redis:"person_id"`
}
type SessionManagement interface {
Get(sessionId int64) SessionData
Save(roomId int64, personId int64) int64
Get(sessionId int64) SessionData
Save(roomId int64, personId int64) (int64, error)
}
type DummySM struct {}
var ctx = context.Background()
func (d DummySM)Get(sessionId int64) SessionData {
const sessionPrefix = "session"
func sessionIdToKey(sessionId int64) string {
return fmt.Sprintf("%s:%d", sessionPrefix, sessionId)
}
type RedisSM struct {
Rdb *redis.Client
}
func (redisSM RedisSM) Get(sessionId int64) SessionData {
var foundSession SessionData
err := redisSM.Rdb.HGetAll(ctx, sessionIdToKey(sessionId)).Scan(foundSession)
if err != nil {
log.Printf("> error reading %d", sessionId)
return SessionData{}
}
log.Printf("> successfully found %d %+v", sessionId, foundSession)
return foundSession
}
func (redisSM RedisSM) Save(roomId int64, personId int64) (int64, error) {
randId := rand.Int63()
newSession := SessionData{
SessionId: randId,
RoomId: roomId,
PersonId: personId,
}
err := redisSM.Rdb.HSet(ctx, sessionIdToKey(randId), newSession).Err()
if err != nil {
log.Printf("> error! saving session %+v %s", newSession, err)
return 0, fmt.Errorf("error saving new session: %+v with %s", newSession, err)
}
return randId, nil
}
type DummySM struct{}
func (d DummySM) Get(sessionId int64) SessionData {
log.Printf("get dummy session by %d", sessionId)
return SessionData{}
}
func (d DummySM)Save(roomId int64, personId int64) int64 {
func (d DummySM) Save(roomId int64, personId int64) (int64, error) {
log.Printf("save dummy session with %d %d", roomId, personId)
return 1
return 1, nil
}