session

package
v0.1.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 19, 2025 License: Apache-2.0 Imports: 11 Imported by: 0

Documentation

Overview

Example
package main

import (
	"context"
	"fmt"
	"net/http"
	"net/http/httptest"
	"time"

	"github.com/halimath/httputils/session"
)

func main() {
	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()

	sessionMiddleware := session.NewMiddleware(
		session.WithStore(session.NewInMemoryStore(
			session.WithContext(ctx),
			session.WithMaxTTL(5*time.Minute),
		)),
	)

	var handler http.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ses := session.FromRequest(r)
		c := session.Get[int](ses, "req_count")
		fmt.Println(c)
		ses.Set("req_count", c+1)
		w.WriteHeader(http.StatusNoContent)
	})

	handler = sessionMiddleware(handler)

	r := httptest.NewRequest("GET", "/", nil)
	w := httptest.NewRecorder()

	handler.ServeHTTP(w, r)
	sessionCookie, err := http.ParseSetCookie(w.Header().Get("Set-Cookie"))
	if err != nil {
		panic(err)
	}

	r = httptest.NewRequest("GET", "/", nil)
	r.AddCookie(sessionCookie)
	w = httptest.NewRecorder()

	handler.ServeHTTP(w, r)

}
Output:

0
1

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrSessionNotFound = errors.New("session not found")

Functions

func GenerateSessionID

func GenerateSessionID() string

GenerateSessionID generates a random, cryptographically secure session id.

func Get

func Get[T any](s Session, key string) (t T)

Get is a generic convenience to get and convert a value from a Session. If key is not found in s or if the value for key in s is not of type T, T’s default value is returned.

func NewMiddleware

func NewMiddleware(opts ...Option) httputils.Middleware

NewMiddleware creates a new HTTP middleware that adds session management. By default, the Store in use is an in-memory store. The session id is stored in a HTTP cookie with the name set to session_id, the path to /, max-age to 5min and SameSite set to strict. Secure is set to true if the request uses HTTPS. Use WithCookieOptions to customize the cookie. HttpOnly is always set to true. The cookie will automatically be prolonged on every request.

The middleware adds the Session associated with each request to the request’s context; use FromContext function to extract the session from this context.

Types

type CookieOpts

type CookieOpts struct {
	Name     string
	Path     string
	Domain   string
	MaxAge   time.Duration
	SameSite http.SameSite
}

type InMemoryStoreOption

type InMemoryStoreOption func(*inMemoryStore)

func WithContext

func WithContext(ctx context.Context) InMemoryStoreOption

func WithMaxTTL

func WithMaxTTL(maxTTL time.Duration) InMemoryStoreOption

type Option

type Option func(*middleware)

Option defines a mutator type to configure a middleware.

func WithCookieOptions

func WithCookieOptions(opts CookieOpts) Option

WithCookieOptions is an Option that customizes the session cookie.

func WithStore

func WithStore(s Store) Option

WithStore is an [Options] that configures the Store to use.

type Session

type Session interface {
	// ID returns the session’s ID.
	ID() string

	// RenewID generates a new ID for this session and stores it. Use this method
	// to renew a sessions’s id after certain events, such as authentication or
	// priviledge changes, as an addition security measure.
	RenewID()

	// Get gets the value associated with key from the Session and returns it
	// if found. The key is not found nil is returned.
	Get(key string) any

	// Set sets the value associated with key to val.
	Set(key string, val any)

	// Delete deletes key from this session.
	Delete(key string)

	// LastAccessed returnes the time stamp this session has been last accessed.
	LastAccessed() time.Time

	// Updates the last accessed timestamp for this session.
	SetLastAccessed(time.Time)
}

Session defines the interface for all session implementations. The design of this interface supports different implementations that include lazy loading or remote storing.

func FromContext

func FromContext(ctx context.Context) Session

FromContext returns the Session associated with ctx. If it does not exist, a nil Session is returned.

func FromRequest

func FromRequest(r *http.Request) Session

FromRequest returns the session associated with r. This is equivalent to

FromContext(r.Context())

func NewInMemorySession

func NewInMemorySession() Session

type Store

type Store interface {
	// Create creates a new session, stores it in this store and returns it.
	Create() (ses Session, err error)

	// Get retrieves the session associated with id and returns it. If id is
	// not found, [ErrSessionNotFound] is returned. If an error occurs while
	// looking up the session, a non-nil error is returned.
	Load(id string) (Session, error)

	// Set sets the session for id to s. If id already exists its value gets
	// overwritten. It returns an error if the operation cannot be performed.
	Store(s Session) error
}

Store defines the interface for session backend storage. It’s the store’s responsibility to synchronize concurrent access accordingly.

func NewInMemoryStore

func NewInMemoryStore(opts ...InMemoryStoreOption) Store

Creates a new in memory session store. Applies opts to customize the store.

This function also spawns a goroutine that periodically checks for old-aged sessions and removes them. The default TTL for no access is 5 minutes. Use the WithMaxTTL option to customize this. Use the WithContext option to pass in a custom context and Cancel this context to stop the goroutine.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL