Feat: save/load state
This commit is contained in:
@ -3,6 +3,7 @@ package handlers
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"golias/models"
|
||||
)
|
||||
|
||||
@ -28,7 +29,44 @@ func getRoomIDFromCtx(ctx context.Context) string {
|
||||
return id
|
||||
}
|
||||
|
||||
func getStateByCtx(ctx context.Context) (*models.UserState, error) {
|
||||
username, ok := ctx.Value(models.CtxUsernameKey).(string)
|
||||
if !ok {
|
||||
log.Debug("no username in ctx")
|
||||
return &models.UserState{}, errors.New("no username in ctx")
|
||||
}
|
||||
us, err := loadState(username)
|
||||
if err != nil {
|
||||
return &models.UserState{}, err
|
||||
}
|
||||
return us, nil
|
||||
}
|
||||
|
||||
// cache
|
||||
|
||||
func saveState(username string, state *models.UserState) error {
|
||||
key := models.CacheStatePrefix + username
|
||||
data, err := json.Marshal(state)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
memcache.Set(key, data)
|
||||
return nil
|
||||
}
|
||||
|
||||
func loadState(username string) (*models.UserState, error) {
|
||||
key := models.CacheStatePrefix + username
|
||||
data, err := memcache.Get(key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp := &models.UserState{}
|
||||
if err := json.Unmarshal(data, &resp); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func getAllNames() []string {
|
||||
names := []string{}
|
||||
// will not scale
|
||||
|
@ -80,6 +80,8 @@ func HandleFrontLogin(w http.ResponseWriter, r *http.Request) {
|
||||
// }
|
||||
// state := models.InitState(cleanName)
|
||||
state := models.MakeTestState()
|
||||
// save state to cache
|
||||
saveState(cleanName, state)
|
||||
tmpl.ExecuteTemplate(w, "base", state)
|
||||
}
|
||||
|
||||
|
@ -2,7 +2,6 @@ package handlers
|
||||
|
||||
import (
|
||||
"golias/config"
|
||||
"golias/models"
|
||||
"golias/pkg/cache"
|
||||
"html/template"
|
||||
"log/slog"
|
||||
@ -57,6 +56,7 @@ func HandleHome(w http.ResponseWriter, r *http.Request) {
|
||||
// tmpl.ExecuteTemplate(w, "room", userState)
|
||||
// return
|
||||
// }
|
||||
userState := models.MakeTestState()
|
||||
// userState := models.MakeTestState()
|
||||
userState, _ := getStateByCtx(r.Context())
|
||||
tmpl.ExecuteTemplate(w, "base", userState)
|
||||
}
|
||||
|
@ -5,5 +5,6 @@ var (
|
||||
CtxUsernameKey = "username"
|
||||
CtxSessionKey = "session"
|
||||
// cache
|
||||
CacheRoomPrefix = "room#"
|
||||
CacheRoomPrefix = "room#"
|
||||
CacheStatePrefix = "state-"
|
||||
)
|
||||
|
Reference in New Issue
Block a user