Middleware.SessionMiddleware
Overview
SessionMiddleware loads and saves session data on each request.
Part of the http package — Node.js analog: express, cors, helmet, morgan.
Method on Middleware — call it on a value of that type after constructing or receiving one from a constructor.
Signature
go
func SessionMiddleware(store SessionStore, opts SessionOptions) MiddlewareCompare: Node.js · Standard Go · gox
js
// Typical express, cors, helmet, morgan pattern in Node.jsgo
func handler(w http.ResponseWriter, r *http.Request) {
// chi or net/http
}go
import "github.com/sahilkhaire/gox/http"
store := NewMemoryStore()
app := New()
app.Use(SessionMiddleware(store, SessionOptions{CookieName: "sid"}))
app.Get("/set", func(c *Ctx) error {
c.Session()["user"] = "alice"
return c.JSON(200, map[string]string{"ok": "1"})
})
app.Get("/get", func(c *Ctx) error {
u, _ := c.Session()["user"].(string)
return c.JSON(200, map[string]string{"user": u})
})
rec := httptest.NewRecorder()Example
go
import "github.com/sahilkhaire/gox/http"
store := NewMemoryStore()
app := New()
app.Use(SessionMiddleware(store, SessionOptions{CookieName: "sid"}))
app.Get("/set", func(c *Ctx) error {
c.Session()["user"] = "alice"
return c.JSON(200, map[string]string{"ok": "1"})
})
app.Get("/get", func(c *Ctx) error {
u, _ := c.Session()["user"].(string)
return c.JSON(200, map[string]string{"user": u})
})
rec := httptest.NewRecorder()Tips
Stack Logger, Recover, and Security middleware the way you would morgan + helmet in Express.
Standard library alternative
Use the standard library directly:
go
func handler(w http.ResponseWriter, r *http.Request) {
// chi or net/http
}