session

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 16, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Save

func Save(r *http.Request, w http.ResponseWriter) error

Save saves all sessions used during the current request.

Types

type Cookie struct {
	// contains filtered or unexported fields
}

Cookie encodes and decodes authenticated and optionally encrypted cookie values.

func NewCookie

func NewCookie(hashKey, blockKey []byte) *Cookie

NewCookie returns a new Cookie.

hashKey is required, used to authenticate values using HMAC. Create it using GenerateRandomKey(). It is recommended to use a key with 32 or 64 bytes.

blockKey is optional, used to encrypt values. Create it using GenerateRandomKey(). The key length must correspond to the key size of the encryption algorithm. For AES, used by default, valid lengths are 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256. The default encoder used for cookie serialization is encoding/gob.

Note that keys created using GenerateRandomKey() are not automatically persisted. NewCookie keys will be created when the application is restarted, and previously issued cookies will not be able to be decoded.

func (*Cookie) BlockFunc

func (s *Cookie) BlockFunc(f func([]byte) (cipher.Block, error)) *Cookie

BlockFunc sets the encryption function used to create a cipher.Block.

Default is crypto/aes.New.

func (*Cookie) Decode

func (s *Cookie) Decode(name, value string, dst any) error

Decode decodes a cookie value.

It decodes, verifies a message authentication code, optionally decrypts and finally deserializes the value.

The name argument is the cookie name. It must be the same name used when it was stored. The value argument is the encoded cookie value. The dst argument is where the cookie will be decoded. It must be a pointer.

func (*Cookie) Encode

func (s *Cookie) Encode(name string, value any) (string, error)

Encode encodes a cookie value.

It serializes, optionally encrypts, signs with a message authentication code, and finally encodes the value.

The name argument is the cookie name. It is stored with the encoded value. The value argument is the value to be encoded. It can be any value that can be encoded using the currently selected serializer; see SetSerializer().

It is the client's responsibility to ensure that value, when encoded using the current serialization/encryption settings on s and then base64-encoded, is shorter than the maximum permissible length.

func (*Cookie) HashFunc

func (s *Cookie) HashFunc(f func() hash.Hash) *Cookie

HashFunc sets the hash function used to create HMAC.

Default is crypto/sha256.New.

func (*Cookie) MaxAge

func (s *Cookie) MaxAge(value int) *Cookie

MaxAge restricts the maximum age, in seconds, for the cookie value.

Default is 86400 * 30. Set it to 0 for no restriction.

func (*Cookie) MaxLength

func (s *Cookie) MaxLength(value int) *Cookie

MaxLength restricts the maximum length, in bytes, for the cookie value.

Default is 4096, which is the maximum value accepted by Internet Explorer.

func (*Cookie) MinAge

func (s *Cookie) MinAge(value int) *Cookie

MinAge restricts the minimum age, in seconds, for the cookie value.

Default is 0 (no restriction).

func (*Cookie) SetSerializer

func (s *Cookie) SetSerializer(sz CookieSerializer) *Cookie

Encoding sets the encoding/serialization method for cookies.

Default is encoding/gob. To encode special structures using encoding/gob, they must be registered first using gob.Register().

type CookieCodec

type CookieCodec interface {
	Encode(name string, value any) (string, error)
	Decode(name, value string, dst any) error
}

CookieCodec defines an interface to encode and decode cookie values.

type CookieError

type CookieError interface {
	error

	// IsUsage returns true for errors indicating the client code probably
	// uses this library incorrectly.  For example, the client may have
	// failed to provide a valid hash key, or may have failed to configure
	// the Serializer adequately for encoding value.
	IsUsage() bool

	// IsDecode returns true for errors indicating that a cookie could not
	// be decoded and validated.  Since cookies are usually untrusted
	// user-provided input, errors of this type should be expected.
	// Usually, the proper action is simply to reject the request.
	IsDecode() bool

	// IsInternal returns true for unexpected errors occurring in the
	// cookie implementation.
	IsInternal() bool

	// Cause, if it returns a non-nil value, indicates that this error was
	// propagated from some underlying library.  If this method returns nil,
	// this error was raised directly by this library.
	//
	// Cause is provided principally for debugging/logging purposes; it is
	// rare that application logic should perform meaningfully different
	// logic based on Cause.  See, for example, the caveats described on
	// (MultiError).Cause().
	Cause() error
}

CookieError is the interface of all errors returned by functions in this library.

type CookieGobEncoder

type CookieGobEncoder struct{}

CookieGobEncoder encodes cookie values using encoding/gob. This is the simplest encoder and can handle complex types via gob.Register.

func (CookieGobEncoder) Deserialize

func (e CookieGobEncoder) Deserialize(src []byte, dst any) error

Deserialize decodes a value using gob.

func (CookieGobEncoder) Serialize

func (e CookieGobEncoder) Serialize(src any) ([]byte, error)

Serialize encodes a value using gob.

type CookieJSONEncoder

type CookieJSONEncoder struct{}

CookieJSONEncoder encodes cookie values using encoding/json. Users who wish to encode complex types need to satisfy the json.Marshaller and json.Unmarshaller interfaces.

func (CookieJSONEncoder) Deserialize

func (e CookieJSONEncoder) Deserialize(src []byte, dst any) error

Deserialize decodes a value using encoding/json.

func (CookieJSONEncoder) Serialize

func (e CookieJSONEncoder) Serialize(src any) ([]byte, error)

Serialize encodes a value using encoding/json.

type CookieNopEncoder

type CookieNopEncoder struct{}

CookieNopEncoder does not encode cookie values, and instead simply accepts a []byte (as an any) and returns a []byte. This is particularly useful when you encoding an object upstream and do not wish to re-encode it.

func (CookieNopEncoder) Deserialize

func (e CookieNopEncoder) Deserialize(src []byte, dst any) error

Deserialize passes a []byte through as-is.

func (CookieNopEncoder) Serialize

func (e CookieNopEncoder) Serialize(src any) ([]byte, error)

Serialize passes a []byte through as-is.

type CookieSerializer

type CookieSerializer interface {
	Serialize(src any) ([]byte, error)
	Deserialize(src []byte, dst any) error
}

CookieSerializer provides an interface for providing custom serializers for cookie values.

type CookieStore

type CookieStore struct {
	Codecs  []CookieCodec
	Options *Options // default configuration
}

CookieStore stores sessions using secure cookies.

func NewCookieStore

func NewCookieStore(keyPairs ...[]byte) *CookieStore

NewCookieStore returns a new CookieStore.

Keys are defined in pairs to allow key rotation, but the common case is to set a single authentication key and optionally an encryption key.

The first key in a pair is used for authentication and the second for encryption. The encryption key can be set to nil or omitted in the last pair, but the authentication key is required in all pairs.

It is recommended to use an authentication key with 32 or 64 bytes. The encryption key, if set, must be either 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256 modes.

func (*CookieStore) Get

func (s *CookieStore) Get(r *http.Request, name string) (*Session, error)

Get returns a session for the given name after adding it to the registry.

It returns a new session if the sessions doesn't exist. Access IsNew on the session to check if it is an existing session or a new one.

It returns a new session and an error if the session exists but could not be decoded.

func (*CookieStore) MaxAge

func (s *CookieStore) MaxAge(age int)

MaxAge sets the maximum age for the store and the underlying cookie implementation. Individual sessions can be deleted by setting Options.MaxAge = -1 for that session.

func (*CookieStore) New

func (s *CookieStore) New(r *http.Request, name string) (*Session, error)

New returns a session for the given name without adding it to the registry.

The difference between New() and Get() is that calling New() twice will decode the session data twice, while Get() registers and reuses the same decoded session after the first call.

func (*CookieStore) Save

func (s *CookieStore) Save(r *http.Request, w http.ResponseWriter,
	session *Session) error

Save adds a single session to the response.

type FilesystemStore

type FilesystemStore struct {
	Codecs  []CookieCodec
	Options *Options // default configuration
	// contains filtered or unexported fields
}

FilesystemStore stores sessions in the filesystem.

It also serves as a reference for custom stores.

This store is still experimental and not well tested. Feedback is welcome.

func NewFilesystemStore

func NewFilesystemStore(path string, keyPairs ...[]byte) *FilesystemStore

NewFilesystemStore returns a new FilesystemStore.

The path argument is the directory where sessions will be saved. If empty it will use os.TempDir().

See NewCookieStore() for a description of the other parameters.

func (*FilesystemStore) Get

func (s *FilesystemStore) Get(r *http.Request, name string) (*Session, error)

Get returns a session for the given name after adding it to the registry.

See CookieStore.Get().

func (*FilesystemStore) MaxAge

func (s *FilesystemStore) MaxAge(age int)

MaxAge sets the maximum age for the store and the underlying cookie implementation. Individual sessions can be deleted by setting Options.MaxAge = -1 for that session.

func (*FilesystemStore) MaxLength

func (s *FilesystemStore) MaxLength(l int)

MaxLength restricts the maximum length of new sessions to l. If l is 0 there is no limit to the size of a session, use with caution. The default for a new FilesystemStore is 4096.

func (*FilesystemStore) New

func (s *FilesystemStore) New(r *http.Request, name string) (*Session, error)

New returns a session for the given name without adding it to the registry.

See CookieStore.New().

func (*FilesystemStore) Save

func (s *FilesystemStore) Save(r *http.Request, w http.ResponseWriter,
	session *Session) error

Save adds a single session to the response.

If the Options.MaxAge of the session is <= 0 then the session file will be deleted from the store path. With this process it enforces the properly session cookie handling so no need to trust in the cookie management in the web browser.

type MultiError

type MultiError []error

MultiError stores multiple errors.

Borrowed from the App Engine SDK.

func (MultiError) Error

func (m MultiError) Error() string

type Options

type Options struct {
	Path   string
	Domain string
	// MaxAge=0 means no Max-Age attribute specified and the cookie will be
	// deleted after the browser session ends.
	// MaxAge<0 means delete cookie immediately.
	// MaxAge>0 means Max-Age attribute present and given in seconds.
	MaxAge   int
	Secure   bool
	HttpOnly bool
	SameSite http.SameSite
}

Options stores configuration for a session or session store.

Fields are a subset of http.Cookie fields.

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry stores sessions used during a request.

func GetRegistry

func GetRegistry(r *http.Request) *Registry

GetRegistry returns a registry instance for the current request.

func (*Registry) Get

func (s *Registry) Get(store Store, name string) (session *Session, err error)

Get registers and returns a session for the given name and session store.

It returns a new session if there are no sessions registered for the name.

func (*Registry) Save

func (s *Registry) Save(w http.ResponseWriter) error

Save saves all sessions registered for the current request.

type Session

type Session struct {
	// The ID of the session, generated by stores. It should not be used for
	// user data.
	ID string
	// Values contains the user-data for the session.
	Values  map[any]any
	Options *Options
	IsNew   bool
	// contains filtered or unexported fields
}

Session stores the values and optional configuration for a session.

func NewSession

func NewSession(store Store, name string) *Session

NewSession is called by session stores to create a new session instance.

func (*Session) AddFlash

func (s *Session) AddFlash(value any, vars ...string)

AddFlash adds a flash message to the session.

A single variadic argument is accepted, and it is optional: it defines the flash key. If not defined "_flash" is used by default.

func (*Session) Flashes

func (s *Session) Flashes(vars ...string) []any

Flashes returns a slice of flash messages from the session.

A single variadic argument is accepted, and it is optional: it defines the flash key. If not defined "_flash" is used by default.

func (*Session) Name

func (s *Session) Name() string

Name returns the name used to register the session.

func (*Session) Save

func (s *Session) Save(r *http.Request, w http.ResponseWriter) error

Save is a convenience method to save this session. It is the same as calling store.Save(request, response, session). You should call Save before writing to the response or returning from the handler.

func (*Session) Store

func (s *Session) Store() Store

Store returns the session store used to register the session.

type Store

type Store interface {
	// Get should return a cached session.
	Get(r *http.Request, name string) (*Session, error)

	// New should create and return a new session.
	//
	// Note that New should never return a nil session, even in the case of
	// an error if using the Registry infrastructure to cache the session.
	New(r *http.Request, name string) (*Session, error)

	// Save should persist session to the underlying store implementation.
	Save(r *http.Request, w http.ResponseWriter, s *Session) error
}

Store is an interface for custom session stores.

See CookieStore and FilesystemStore for examples.

Jump to

Keyboard shortcuts

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