Session | Echo
Session middleware facilitates HTTP session management backed by gorilla sessions. The default implementation provides cookie and filesystem based session store; however, you can take advantage of community maintained implementation for various backends.
Function to create session middleware and utility function to get session from context:
func NewSessionMiddleware(store sessions.Store) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
c.Set("_session_store", store)
return next(c)
}
}
}
func GetSession(c *echo.Context, name string) (*sessions.Session, error) {
store, err := echo.ContextGet[sessions.Store](c, "_session_store")
if err != nil {
return nil, err
}
return store.Get(c.Request(), name)
}
This example exposes two endpoints: /create-session creates new session and /read-session read value from
session if request contains session id.
package main
import (
"fmt"
"net/http"
"github.com/gorilla/sessions"
"github.com/labstack/echo/v5"
)
func NewSessionMiddleware(store sessions.Store) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c *echo.Context) error {
c.Set("_session_store", store)
return next(c)
}
}
}
func GetSession(c *echo.Context, name string) (*sessions.Session, error) {
store, err := echo.ContextGet[sessions.Store](c, "_session_store")
if err != nil {
return nil, fmt.Errorf("failed to get session store: %w", err)
}
return store.Get(c.Request(), name)
}
func main() {
e := echo.New()
sessionStore := sessions.NewCookieStore([]byte("secret"))
e.Use(NewSessionMiddleware(sessionStore))
e.GET("/create-session", func(c *echo.Context) error {
sess, err := GetSession(c, "session")
if err != nil {
return err
}
sess.Options = &sessions.Options{
Path: "/",
MaxAge: 86400 * 7,
HttpOnly: true,
}
sess.Values["foo"] = "bar"
if err := sess.Save(c.Request(), c.Response()); err != nil {
return err
}
return c.NoContent(http.StatusOK)
})
e.GET("/read-session", func(c *echo.Context) error {
sess, err := GetSession(c, "session")
if err != nil {
return err
}
return c.String(http.StatusOK, fmt.Sprintf("foo=%v\n", sess.Values["foo"]))
})
if err := e.Start(":8080"); err != nil {
e.Logger.Error("failed to start server", "error", err)
}
}
Requesting /read-session without providing session it will output nil as foo value
Using session cookie from previous response and requesting /read-session will output foo value from session.