Documentation
¶
Index ¶
- type Codec
- type Cookie
- type Flashes
- type Manager
- func (m *Manager[Data]) Client(data Data) (*http.Client, error)
- func (m *Manager[Data]) Delete(ctx context.Context, id string) (err error)
- func (m *Manager[Data]) From(ctx context.Context) (session *Data)
- func (m *Manager[Data]) FromRequest(r Request) (session *Data)
- func (m *Manager[Data]) Load(ctx context.Context, id string) (*Session[*Data], error)
- func (m *Manager[Data]) Middleware(next http.Handler) http.Handler
- func (m *Manager[Data]) Read(r Request) (session *Session[*Data], err error)
- func (m *Manager[Data]) Save(ctx context.Context, session *Session[*Data]) (err error)
- func (m *Manager[Data]) Transport(data Data) (http.RoundTripper, error)
- func (m *Manager[Data]) Write(w ResponseWriter, r Request, session *Session[*Data]) (err error)
- type Request
- type ResponseWriter
- type Session
- type Store
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Codec ¶
Codec encodes session payloads for the store. Encoding the same value must produce the same bytes, so unchanged sessions aren't saved again.
type Cookie ¶
type Cookie struct {
// Name sets the name of the session cookie. It should not contain
// whitespace, commas, colons, semicolons, backslashes, the equals sign or
// control characters as per RFC6265. The default cookie name is "session".
// If your application uses two different sessions, you must make sure that
// the cookie name for each is unique.
Name string
// Domain sets the 'Domain' attribute on the session cookie. By default
// it will be set to the domain name that the cookie was issued from.
Domain string
// HttpOnly sets the 'HttpOnly' attribute on the session cookie. The
// default value is true.
HttpOnly bool
// Path sets the 'Path' attribute on the session cookie. The default value
// is "/". Passing the empty string "" will result in it being set to the
// path that the cookie was issued from.
Path string
// Persist sets whether the session cookie should be persistent or not
// (i.e. whether it should be retained after a user closes their browser).
// The default value is true, which means that the session cookie will not
// be destroyed when the user closes their browser and the appropriate
// 'Expires' and 'MaxAge' values will be added to the session cookie. If you
// want to only persist some sessions (rather than all of them), then set this
// to false and call the RememberMe() method for the specific sessions that you
// want to persist.
ExpireIn time.Duration
// SameSite controls the value of the 'SameSite' attribute on the session
// cookie. By default this is set to 'SameSite=Lax'. If you want no SameSite
// attribute or value in the session cookie then you should set this to 0.
SameSite http.SameSite
// Secure sets the 'Secure' attribute on the session cookie. The default
// value is false. It's recommended that you set this to true and serve all
// requests over HTTPS in production environments.
// See https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Session_Management_Cheat_Sheet.md#transport-layer-security.
Secure bool
}
Cookie contains the configuration settings for session cookies.
type Flashes ¶ added in v0.1.1
Flashes holds string values by case-sensitive key. Initialize it before calling Set or Add, for example with make(Flashes).
func (Flashes) Get ¶ added in v0.1.1
Get returns the first value for key, or an empty string if none exists.
type Manager ¶
type Manager[Data any] struct { Cookie *Cookie Store Store Codec Codec Flash *flashManager[Data] // ErrorHandler is called when an error occurs in the middleware. Once the // response has started, what it writes is discarded, so it should also log. // Default is to log and return a 500 status code with the error message. ErrorHandler func(http.ResponseWriter, *http.Request, error) // Now is used to get the current time. This is useful for testing. Now func() time.Time // Generate is used to generate a new session id. Generate func() (string, error) }
Manager manages sessions
func (*Manager[Data]) FromRequest ¶ added in v0.1.0
FromRequest returns the session data from the request
func (*Manager[Data]) Middleware ¶
Middleware loads the session and saves it when it changes. The response is not buffered, so the session is saved right before the headers are written. Make changes that need a cookie, such as logging in, before writing the body. Later changes to an existing session are saved when the handler returns. Later changes to a new session can't set a cookie, so they're reported to ErrorHandler instead.
type ResponseWriter ¶
ResponseWriter is the minimal interface required for setting cookies
type Session ¶
type Session[Data any] struct { ID string // Will be empty if the session is new Data Data Expiry time.Time // contains filtered or unexported fields }
Example ¶
package main
import (
"net/http"
"github.com/matthewmueller/sesh"
)
func main() {
type User struct {
ID int `json:"id"`
Name string `json:"name"`
}
type Data struct {
User *User
}
sessions := sesh.New[Data]()
router := http.NewServeMux()
// Login a user
router.HandleFunc("POST /sessions", func(w http.ResponseWriter, r *http.Request) {
session := sessions.FromRequest(r)
// Assumes we've loaded and authenticated the user
session.User = &User{
ID: 1,
Name: "Alice",
}
http.Redirect(w, r, "/", http.StatusFound)
})
// Show the user if they're logged in
router.HandleFunc("GET /", func(w http.ResponseWriter, r *http.Request) {
session := sessions.FromRequest(r)
if session.User != nil {
w.Write([]byte("Welcome " + session.User.Name))
return
}
w.Write([]byte("Welcome!"))
})
handler := sessions.Middleware(router)
http.ListenAndServe(":8080", handler)
}
Output:
type Store ¶
type Store interface {
// Find should return the data for a session id from the store. If the
// session id is not found, expired or tampered, the data will be nil and the
// time will be zero, but there will be no error. The err return value should
// be used for system errors only.
Find(ctx context.Context, id string) (data []byte, expiry time.Time, err error)
// Upsert the session id data and expiry to the store, with the given If the
// session id already exists, then the data and expiry time should be
// overwritten.
Upsert(ctx context.Context, id string, data []byte, expiry time.Time) (err error)
// Delete removes the session id and corresponding data from the session
// store. If the id does not exist then Delete should be a no-op and return
// nil (not an error).
Delete(ctx context.Context, id string) (err error)
}
Store is the interface for session stores.