我正在尝试使用 sessions middleware对于 echo web framework 。中间件本质上只是 gorilla/sessions 的包装。专为与 echo 配合使用而定制。
我基本上只是复制了文档中给出的示例并对其进行了稍微扩展。
e := echo.New()
e.Use(session.Middleware(sessions.NewCookieStore([]byte("Secret"))))
// Add the name "Steve" to the session
e.GET("/login", func(c echo.Context) error {
sess, err := session.Get("session", c)
if err != nil {
return err
}
sess.Options = &sessions.Options{
Path: "/",
MaxAge: 0,
HttpOnly: false,
Secure: true,
}
sess.Values["name"] = "Steve"
sess.Save(c.Request(), c.Response())
return c.NoContent(http.StatusOK)
})
// Reply with the name saved in the session
e.GET("/whoami", func(c echo.Context) error {
sess, err := session.Get("session", c)
if err != nil {
return err
}
return c.JSON(http.StatusOK, sess.Values["name"])
})
我希望首先访问 /login
将名称保存到 session 中,然后访问 /whoami
并接收名称 "Steve"
.
/login
按预期返回 StatusOK
,但 /whoami
始终返回 null
。为什么名称没有保存到 session 中?
最佳答案
该问题是由设置 session.Option.Secure = true
引起的。
我正在本地测试,没有使用 HTTPS
,因此未设置 cookie。
关于session - Echo session 中间件不保存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55435990/