回声会话中间件未保存

时间:2019-03-30 21:56:19

标签: session go gorilla go-echo

我正在尝试将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以将名称保存到会话中,然后访问/whoami并获得名称"Steve"

/login返回预期的StatusOK,但是/whoami始终返回null。为什么不将名称保存到会话中?

1 个答案:

答案 0 :(得分:0)

此问题是由设置class BillBundle { public final int fives; public final int tens; public final int twenties; public final int fifties; public BillBundle(int fives, int tens, int twenties, int fifties) { this.fives = fives; this.tens = tens; this.twenties = twenties; this.fifties = fifties; } } 引起的。

我正在本地测试,未使用public class MyRandomGenerator { private static readonly Random _randomGenerator = new Random(); public static float NextFloat() { var randomValue = _randomGenerator.NextDouble() - 0.5d; return (float)randomValue; } } ,因此未设置cookie。