duanluo5096 2019-03-30 13:56
浏览 65
已采纳

回声会话中间件未保存

I am trying to use the sessions middleware for the echo web framework. The middleware is essentially just a wrapper around gorilla/sessions tailored to work with echo.

I have basically just copied the example given in the documentation and extended it slightly.


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"])
    })

I expect to first visit /login to save the name to the session, and then visit /whoami and receive the name "Steve".

/login returns StatusOK as expected, but /whoami always returns null. Why isn't the name being saved to the session?

展开全部

  • 写回答

1条回答 默认 最新

  • douchuang4181 2019-03-30 17:58
    关注

    The issue is caused by settings session.Option.Secure = true.

    I am testing locally and not using HTTPS so the cookie is not being set.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?