Session (会话) 中间件

Session 中间件促进了 gorilla/sessions 支持的 HTTP 会话管理。默认提供了基于 cookie 与文件系统的会话存储;然而,你也可以访问 community maintained implementation 来参考其各式各样的后端实现。

Echo 社区贡献

依赖

  1. import (
  2. "github.com/gorilla/sessions"
  3. "github.com/labstack/echo-contrib/session"
  4. )

用法

  1. e := echo.New()
  2. e.Use(session.Middleware(sessions.NewCookieStore([]byte("secret"))))
  3. e.GET("/", func(c echo.Context) error {
  4. sess, _ := session.Get("session", c)
  5. sess.Options = &sessions.Options{
  6. Path: "/",
  7. MaxAge: 86400 * 7,
  8. HttpOnly: true,
  9. }
  10. sess.Values["foo"] = "bar"
  11. sess.Save(c.Request(), c.Response())
  12. return c.NoContent(http.StatusOK)
  13. })

Custom Configuration

用法

  1. e := echo.New()
  2. e.Use(session.MiddlewareWithConfig(session.Config{}))

配置

  1. Config struct {
  2. // Skipper defines a function to skip middleware.
  3. Skipper middleware.Skipper
  4. // Session store.
  5. // Required.
  6. Store sessions.Store
  7. }

默认配置

  1. DefaultConfig = Config{
  2. Skipper: DefaultSkipper,
  3. }