From 5ebf6b04316a1414602e85351d448b61704a711a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=90=E6=B6=9B?= Date: Thu, 11 Aug 2022 17:33:32 +0800 Subject: [PATCH] =?UTF-8?q?feat(cache):=E5=A2=9E=E5=8A=A0=E5=90=91redis?= =?UTF-8?q?=E4=BF=9D=E5=AD=98=E7=94=A8=E6=88=B7=E4=BC=9A=E8=AF=9D=E7=9A=84?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- cache/session.go | 42 ++++++++++++++++++++++++++++++++++++++++++ model/session.go | 11 +++++++++++ 2 files changed, 53 insertions(+) create mode 100644 cache/session.go create mode 100644 model/session.go 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"` +}