【问题标题】:How to save a session in golang如何在 golang 中保存会话
【发布时间】:2019-01-18 23:28:32
【问题描述】:

我正在尝试使用 gorilla 会话和 securecookie 在我的 golang 后端保存记录的用户 ID。

这是我的打包会话:

package session

import (
    "fmt"
    "net/http"

    "github.com/gorilla/securecookie"
    "github.com/gorilla/sessions"
)

var store = sessions.NewCookieStore(securecookie.GenerateRandomKey(32))

//GetSessionLoggedID returns loggedID
func 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 ID
func 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 是正确的。但是会话没有像我希望的那样保存。

如果我在 checkpassword 函数的末尾添加 session.GetSessionLoggedID(r),我会得到“未找到”。

我错过了什么?

【问题讨论】:

    标签: session go gorilla


    【解决方案1】:
    // watch this line
    if auth, ok := storeAuth.Values["loggedID"].(bool); ok && auth {
    

    storeAuth.Values["loggedID"] 不是bool,所以okfalse,然后你会得到“找不到”

    改成

        if auth, ok := storeAuth.Values["loggedID"]; ok{
            return auth.(int)
        }
        fmt.Println("none found")
    

    【讨论】:

      猜你喜欢
      • 2014-03-18
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 2017-10-20
      • 2017-12-31
      • 1970-01-01
      相关资源
      最近更新 更多