亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 golang 中保存會話

如何在 golang 中保存會話

Go
萬千封印 2023-06-01 17:09:55
我正在嘗試使用大猩猩會話和 securecookie 在我的 golang 后端中保存已登錄的用戶 ID。這是我的包裹會議:package sessionimport (    "fmt"    "net/http"    "github.com/gorilla/securecookie"    "github.com/gorilla/sessions")var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(32))//GetSessionLoggedID returns loggedIDfunc GetSessionLoggedID(r *http.Request) int {    storeAuth, _ := store.Get(r, "authentication")    if auth, ok := storeAuth.Values["loggedID"].(bool); ok && auth {        return storeAuth.Values["loggedID"].(int)    }    fmt.Println("none found")    return 0}//SetSessionLoggedID sets cookie session user IDfunc SetSessionLoggedID(w http.ResponseWriter, r *http.Request, id int) {    storeAuth, err := store.Get(r, "authentication")    if err != nil {        fmt.Println(err.Error())    }    storeAuth.Options = &sessions.Options{HttpOnly: true, Secure: true, MaxAge: 2628000, Path: "/"}    storeAuth.Values["loggedID"] = id    storeAuth.Save(r, w)}我有另一個包可以驗證登錄用戶的電子郵件/密碼。這是功能:func (handler *UserHandler) checkPassword(w http.ResponseWriter, r *http.Request) {    var body struct {        Email    string        Password string    }    err := json.NewDecoder(r.Body).Decode(&body)    if err != nil {        http.Error(w, err.Error(), http.StatusInternalServerError)        return    }    loggedID, err := handler.UserUsecase.PasswordMatch(body.Email, body.Password)    if err != nil || loggedID == 0 {        http.Error(w, "Could not authenticate user", http.StatusUnauthorized)        return    }    session.SetSessionLoggedID(w, r, loggedID)    json.NewEncoder(w).Encode(struct {        ID int `json:"id"`    }{loggedID})}返回的 ID 是正確的。但是會話并沒有像我希望的那樣保存。session.GetSessionLoggedID(r)如果我在 checkpassword 函數的末尾添加一個,我會得到“未找到”。我錯過了什么?
查看完整描述

1 回答

?
波斯汪

TA貢獻1811條經驗 獲得超4個贊

// watch this line

if auth, ok := storeAuth.Values["loggedID"].(bool); ok && auth {

storeAuth.Values["loggedID"]不是bool,ok也是false,然后你得到“未找到”


改成


    if auth, ok := storeAuth.Values["loggedID"]; ok{

        return auth.(int)

    }

    fmt.Println("none found")


查看完整回答
反對 回復 2023-06-01
  • 1 回答
  • 0 關注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號