1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| package session
import ( "context" "crypto/rand" "encoding/base64" "github.com/go-redis/redis/v8" "time" )
const SessionPrefix = "session:"
type Session struct { ID string UserID uint CreatedAt time.Time ExpiresAt time.Time }
func GenerateSessionID() (string, error) { b := make([]byte, 32) _, err := rand.Read(b) if err != nil { return "", err } return base64.URLEncoding.EncodeToString(b), nil }
func CreateSession(ctx context.Context, userID uint, redisClient *redis.Client) (*Session, error) { id, err := GenerateSessionID() if err != nil { return nil, err }
session := &Session{ ID: id, UserID: userID, CreatedAt: time.Now(), ExpiresAt: time.Now().Add(24 * time.Hour), }
key := SessionPrefix + id err = redisClient.Set(ctx, key, userID, 24*time.Hour).Err() if err != nil { return nil, err }
return session, nil }
func GetSession(ctx context.Context, sessionID string, redisClient *redis.Client) (*Session, error) { key := SessionPrefix + sessionID userID, err := redisClient.Get(ctx, key).Uint64() if err == redis.Nil { return nil, nil } else if err != nil { return nil, err }
return &Session{ ID: sessionID, UserID: uint(userID), CreatedAt: time.Now(), ExpiresAt: time.Now().Add(24 * time.Hour), }, nil }
func DeleteSession(ctx context.Context, sessionID string, redisClient *redis.Client) error { key := SessionPrefix + sessionID return redisClient.Del(ctx, key).Err() }
|