diff --git a/handlers/actions.go b/handlers/actions.go index b74d9da..0b22ded 100644 --- a/handlers/actions.go +++ b/handlers/actions.go @@ -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 diff --git a/handlers/auth.go b/handlers/auth.go index a790900..8dca6f5 100644 --- a/handlers/auth.go +++ b/handlers/auth.go @@ -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) } diff --git a/handlers/handlers.go b/handlers/handlers.go index 261990c..286e352 100644 --- a/handlers/handlers.go +++ b/handlers/handlers.go @@ -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) } diff --git a/models/keys.go b/models/keys.go index 52a0665..400886e 100644 --- a/models/keys.go +++ b/models/keys.go @@ -5,5 +5,6 @@ var ( CtxUsernameKey = "username" CtxSessionKey = "session" // cache - CacheRoomPrefix = "room#" + CacheRoomPrefix = "room#" + CacheStatePrefix = "state-" )