diff --git a/cache/session.go b/cache/session.go new file mode 100644 index 0000000..6a54037 --- /dev/null +++ b/cache/session.go @@ -0,0 +1,42 @@ +package cache + +import ( + "electricity_bill_calc/global" + "electricity_bill_calc/model" + "fmt" + "time" + + "github.com/go-redis/redis/v8" + "github.com/vmihailenco/msgpack/v5" +) + +func CacheSession(session *model.Session) error { + key := fmt.Sprintf("session:%s", session.Token) + serializedSession, err := msgpack.Marshal(session) + + if err != nil { + return err + } + + validRemains := time.Until(session.ExpiresAt) + cmd := global.RedisConn.SetNX(global.Ctx, key, serializedSession, validRemains) + return cmd.Err() +} + +func RetreiveSession(token string) (*model.Session, error) { + key := fmt.Sprintf("session:%s", token) + result, err := global.RedisConn.Get(global.Ctx, key).Result() + if err != nil { + if err == redis.Nil { + return nil, nil + } else { + return nil, err + } + } + session := &model.Session{} + err = msgpack.Unmarshal([]byte(result), session) + if err != nil { + return nil, err + } + return session, nil +} diff --git a/model/session.go b/model/session.go new file mode 100644 index 0000000..9f15dc9 --- /dev/null +++ b/model/session.go @@ -0,0 +1,11 @@ +package model + +import "time" + +type Session struct { + Uid string `json:"uid"` + Name string `json:"name"` + Type int8 `json:"type"` + Token string `json:"token"` + ExpiresAt time.Time `json:"expiresAt"` +}