Documentation
¶
Index ¶
- Variables
- func Save(w http.ResponseWriter, r *http.Request) error
- type Block
- type BlockKey
- type Codec
- type CodecOption
- func WithBlock(block cipher.Block) CodecOption
- func WithBlockKey(key []byte) CodecOption
- func WithHashFn(fn func() hash.Hash) CodecOption
- func WithMaxAge(age int64) CodecOption
- func WithMaxLength(length int) CodecOption
- func WithMinAge(age int64) CodecOption
- func WithSerializer(s Serializer) CodecOption
- type CookieOptions
- type CookieStore
- type FileSystemStore
- type Flash
- func (f *Flash) Add(key, message string)
- func (f *Flash) BinaryMarshal() ([]byte, error)
- func (f *Flash) BinaryUnmarshal(data []byte) error
- func (f *Flash) Clear()
- func (f *Flash) Get(key string) string
- func (f *Flash) GobDecode(data []byte) error
- func (f *Flash) GobEncode() ([]byte, error)
- func (f *Flash) Keep(key, message string)
- func (f *Flash) MarshalJSON() ([]byte, error)
- func (f *Flash) Now(key, message string)
- func (f *Flash) Remove(key string)
- func (f *Flash) UnmarshalJSON(data []byte) error
- type GobSerializer
- type HashFn
- type JsonSerializer
- type MaxAge
- type MaxLength
- type MinAge
- type Serializer
- type SerializerOption
- type Session
- type SessionManager
- type SessionProxy
- type Store
Constants ¶
This section is empty.
Variables ¶
var ( ErrHashKeyNotSet = errors.ErrInternalServerError.Msg("the hash key is not set for the codec") ErrEncodedLengthTooLong = errors.ErrOutOfRange.Msg("the encoded value is too long") ErrSerializeFailed = errors.ErrInternalServerError.Msg("the value cannot be serialized") ErrDeserializeFailed = errors.ErrInternalServerError.Msg("the value cannot be deserialized") ErrHMACIsInvalid = errors.ErrBadRequest.Msg("the value cannot be validated") ErrTimestampIsInvalid = errors.ErrBadRequest.Msg("the timestamp is invalid") ErrTimestampIsTooNew = errors.ErrOutOfRange.Msg("the timestamp is too new") ErrTimestampIsExpired = errors.ErrOutOfRange.Msg("the timestamp has expired") ErrCreatingBlockCipher = errors.ErrInternalServerError.Msg("failed to create block cipher") ErrGeneratingIV = errors.ErrInternalServerError.Msg("error generating the random iv") ErrDecryptionFailed = errors.ErrInternalServerError.Msg("the value cannot be decrypted") ErrNoCodecs = errors.ErrInternalServerError.Msg("no codecs were provided") ErrNoResponseWriter = errors.ErrInternalServerError.Msg("no response writer was provided") ErrInvalidSessionType = errors.ErrBadRequest.Msg("the session type is incorrect") )
var DefaultDomain = ""
var DefaultHashFn = sha256.New
Codec Defaults
var DefaultHttpOnly = true
var DefaultMaxAge = 86400 * 30 // 30 days
Cookie Defaults
var DefaultMaxLength = 4096
var DefaultPartitioned = false
var DefaultPath = "/"
Session Defaults
var DefaultSameSite = http.SameSiteLaxMode
var DefaultSecure = false
Functions ¶
Types ¶
type Codec ¶
type Codec interface { Encode(name string, src any) ([]byte, error) Decode(name string, src []byte, dst any) error }
func NewCodec ¶
func NewCodec(hashKey []byte, options ...CodecOption) Codec
NewCodec returns a new Codec set up with the hash key, optionally configured with additional provided CodecOption options.
Codecs are used to encode and optionally encrypt session values. The hashKey is required and used to authenticate the cookie value using HMAC. It is recommended to use a key with 32 or 64 bytes.
The blockKey is optional and used to encrypt the cookie value. If set, the length must correspond to the block 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.
Either options or setting sessions.Default* values can be used to configure the codec.
type CodecOption ¶
type CodecOption interface {
// contains filtered or unexported methods
}
CodecOption is an option for configuring a codec.
The following options are available: - WithMaxAge: sets the maximum age of the session cookie - WithMinAge: sets the minimum age of the session cookie - WithMaxLength: sets the maximum length of the session cookie - WithHashFn: sets the hash function used by the codec - WithBlockKey: sets the block key used by the codec; aes.NewCipher is used to create the block cipher - WithBlock: sets the block cipher used by the codec - WithSerializer: sets the serializer used by the codec
func WithBlock ¶
func WithBlock(block cipher.Block) CodecOption
WithBlock sets the block cipher used by the codec.
The block cipher is used to encrypt the session cookie.
If the block cipher is nil, the session cookie is not encrypted.
func WithBlockKey ¶
func WithBlockKey(key []byte) CodecOption
WithBlockKey sets the block key used by the codec.
Recommended key sizes are 16, 24, or 32 bytes to select AES-128, AES-192, or AES-256.
func WithHashFn ¶
func WithHashFn(fn func() hash.Hash) CodecOption
WithHashFn sets the hash function used by the codec during the steps where a HMAC is calculated.
The default hash function is sha256.New.
func WithMaxAge ¶
func WithMaxAge(age int64) CodecOption
WithMaxAge sets the maximum age of the session cookie.
The age is in seconds.
func WithMaxLength ¶
func WithMaxLength(length int) CodecOption
WithMaxLength sets the maximum length of the session cookie.
If the length is 0, there is no limit to the size of a session.
func WithMinAge ¶
func WithMinAge(age int64) CodecOption
WithMinAge sets the minimum age of the session cookie.
The age is in seconds.
func WithSerializer ¶
func WithSerializer(s Serializer) CodecOption
WithSerializer sets the serializer used by the codec.
The serializer is used to serialize and deserialize the session cookie values.
type CookieOptions ¶
type CookieOptions struct { Name string Path string Domain string MaxAge int Secure bool HttpOnly bool Partitioned bool SameSite http.SameSite }
func NewCookieOptions ¶
func NewCookieOptions() CookieOptions
NewCookieOptions returns a new CookieOptions with default values.
The default values are:
- Name: ""
- Path: "/"
- Domain: ""
- MaxAge: 86400 * 30
- Secure: false
- HttpOnly: true
- Partitioned: false
- SameSite: http.SameSiteLaxMode
type CookieStore ¶
type CookieStore struct{}
func NewCookieStore ¶
func NewCookieStore() *CookieStore
func (CookieStore) Get ¶
func (cs CookieStore) Get(_ context.Context, proxy *SessionProxy, cookieValue string) error
func (CookieStore) New ¶
func (cs CookieStore) New(_ context.Context, _ *SessionProxy) error
func (CookieStore) Save ¶
func (cs CookieStore) Save(_ context.Context, proxy *SessionProxy) error
type FileSystemStore ¶
type FileSystemStore struct {
// contains filtered or unexported fields
}
func NewFileSystemStore ¶
func NewFileSystemStore(root string, maxFileSize int) *FileSystemStore
func (FileSystemStore) Get ¶
func (fs FileSystemStore) Get(_ context.Context, proxy *SessionProxy, cookieValue string) error
func (FileSystemStore) New ¶
func (fs FileSystemStore) New(_ context.Context, _ *SessionProxy) error
func (FileSystemStore) Save ¶
func (fs FileSystemStore) Save(_ context.Context, proxy *SessionProxy) error
type Flash ¶ added in v0.2.0
type Flash struct {
// contains filtered or unexported fields
}
Flash is used to store messages for the current and next request
Three types of messages can be stored: - Current request only: Add these messages with the Now(key, message) method. - Next request only: Add these messages with the Add(key, message) method. - Until read or removed: Add these messages with the Keep(key, message) method.
func (*Flash) Add ¶ added in v0.2.0
Add adds a flash message for the given key
The stored flash message will be available until the next request.
func (*Flash) BinaryMarshal ¶ added in v0.2.0
BinaryMarshal encodes the flash messages for binary serialization
func (*Flash) BinaryUnmarshal ¶ added in v0.2.0
BinaryUnmarshal decodes the flash messages for binary serialization
func (*Flash) Get ¶ added in v0.2.0
Get returns the flash message for the given key and deletes the message from the flash storage
func (*Flash) GobDecode ¶ added in v0.2.0
GobDecode decodes the flash messages for gob serialization
func (*Flash) GobEncode ¶ added in v0.2.0
GobEncode encodes the flash messages for gob serialization
func (*Flash) Keep ¶ added in v0.2.0
Keep adds a flash message for the given key
The stored flash message will be available until the message is read or removed.
func (*Flash) MarshalJSON ¶ added in v0.2.0
MarshalJSON encodes the flash messages for json serialization
func (*Flash) Now ¶ added in v0.2.0
Now adds a flash message for the given key
The stored flash message will be available only for the current request.
func (*Flash) UnmarshalJSON ¶ added in v0.2.0
UnmarshalJSON decodes the flash messages for json serialization
type GobSerializer ¶
type GobSerializer struct{}
GobSerializer is a serializer that uses the encoding/gob package to serialize and deserialize session values.
Note that the gob package requires that the type being serialized is registered with gob.Register.
Example:
type MySessionData struct { // fields ... } func init() { gob.Register(MySessionData{}) }
func (GobSerializer) Deserialize ¶
func (s GobSerializer) Deserialize(src []byte, dst any) error
type JsonSerializer ¶
type JsonSerializer struct{}
JsonSerializer is a serializer that uses the encoding/json package to serialize and deserialize session values.
func (JsonSerializer) Deserialize ¶
func (s JsonSerializer) Deserialize(src []byte, dst any) error
type Serializer ¶
Serializer is an interface for encoding and decoding session values. They are used by the Codec to serialize and deserialize session values.
The following two implementations are provided:
- JsonSerializer
- GobSerializer
You can also implement your own serializer if you have specific requirements. Use WithSerializer to set a custom serializer when creating a new codec.
var DefaultSerializer Serializer = JsonSerializer{}
type SerializerOption ¶
type SerializerOption struct {
Serializer
}
type Session ¶
func (*Session[T]) Delete ¶
Delete will delete the session from the store and the response.
This is a convenience method that sets the MaxAge of the session to -1 and saves the session.
func (*Session[T]) DoNotPersist ¶
func (s *Session[T]) DoNotPersist()
DoNotPersist will set the MaxAge of the session to 0, signaling to the store that the session should not be persisted.
This is useful for situations where you have implemented a "Remember Me" feature and have defaulted the manager to persist sessions.
func (*Session[T]) Expire ¶
func (s *Session[T]) Expire()
Expire will set the MaxAge of the session to -1, effectively deleting the session next time it is saved.
type SessionManager ¶
type SessionManager[T any] interface { Get(r *http.Request) (*Session[T], error) Save(w http.ResponseWriter, r *http.Request, session *Session[T]) error }
func NewSessionManager ¶
func NewSessionManager[T any](options CookieOptions, store Store, codecs ...Codec) SessionManager[T]
type SessionProxy ¶
type SessionProxy struct { ID string Values any IsNew bool // contains filtered or unexported fields }
func (*SessionProxy) Decode ¶
func (sp *SessionProxy) Decode(data []byte, dst any) error
Decode will decode the data into the dst value.
Codecs that have been configured for this session will be used.
This should be used to read the session value from the request. Example:
err := proxy.Decode([]byte(cookieValue), proxy.Values) if err != nil { return err }
Useful destinations are the Values and ID fields of the SessionProxy.
func (*SessionProxy) Delete ¶
func (sp *SessionProxy) Delete() error
Delete will delete the session cookie regardless of its MaxAge.
func (*SessionProxy) Encode ¶
func (sp *SessionProxy) Encode(src any) ([]byte, error)
Encode will encode the src value into a byte slice.
Codecs that have been configured for this session will be used.
This should be called before calling Save. Example:
encoded, err := proxy.Encode(proxy.Values) if err != nil { return err } return proxy.Save(string(encoded))
func (*SessionProxy) IsExpired ¶
func (sp *SessionProxy) IsExpired() bool
func (*SessionProxy) MaxAge ¶
func (sp *SessionProxy) MaxAge() int
func (*SessionProxy) Save ¶
func (sp *SessionProxy) Save(value string) error
Save will write the session value into a cookie and to the response writer.
The cookie will be deleted if the cookie is expired based on its MaxAge.
type Store ¶
type Store interface { Get(ctx context.Context, proxy *SessionProxy, cookieValue string) error New(ctx context.Context, proxy *SessionProxy) error Save(ctx context.Context, proxy *SessionProxy) error }