Documentation
¶
Overview ¶
Package redistore is a session store backend for gorilla/sessions
Index ¶
- func Keys(keys ...[]byte) [][]byte
- func KeysFromStrings(keys ...string) [][]byte
- type GobSerializer
- type JSONSerializer
- type Option
- func WithAddress(network, address string) Option
- func WithAuth(username, password string) Option
- func WithDB(db string) Option
- func WithDBNum(dbNum int) Option
- func WithDefaultMaxAge(age int) Option
- func WithIdleTimeout(timeout time.Duration) Option
- func WithKeyPrefix(prefix string) Option
- func WithMaxAge(age int) Option
- func WithMaxLength(length int) Option
- func WithPassword(password string) Option
- func WithPath(path string) Option
- func WithPool(pool *redis.Pool) Option
- func WithPoolSize(size int) Option
- func WithSerializer(serializer SessionSerializer) Option
- func WithSessionOptions(opts *sessions.Options) Option
- func WithURL(url string) Option
- type RediStore
- func (s *RediStore) Close() error
- func (s *RediStore) Delete(r *http.Request, w http.ResponseWriter, session *sessions.Session) error
- func (s *RediStore) Get(r *http.Request, name string) (*sessions.Session, error)
- func (s *RediStore) New(r *http.Request, name string) (*sessions.Session, error)
- func (s *RediStore) Save(r *http.Request, w http.ResponseWriter, session *sessions.Session) error
- func (s *RediStore) SetKeyPrefix(p string)
- func (s *RediStore) SetMaxAge(v int)
- func (s *RediStore) SetMaxLength(l int)
- func (s *RediStore) SetSerializer(ss SessionSerializer)
- type SessionSerializer
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Keys ¶
Keys creates a key pairs slice from individual byte slices. This is a convenience function to simplify the creation of key pairs without having to write [][]byte{...}.
Example:
store, err := NewStore(
Keys([]byte("auth-key"), []byte("encrypt-key")),
WithAddress("tcp", ":6379"),
)
func KeysFromStrings ¶
KeysFromStrings creates a key pairs slice from strings. This is the most convenient way to provide keys for development and testing.
Warning: For production use with sensitive keys, consider using Keys() with byte slices loaded from secure storage instead of hardcoded strings.
Example:
// Single key
store, err := NewStore(
KeysFromStrings("secret-key"),
WithAddress("tcp", ":6379"),
)
// Multiple keys for rotation
store, err := NewStore(
KeysFromStrings(
"new-auth-key",
"new-encrypt-key",
"old-auth-key",
"old-encrypt-key",
),
WithAddress("tcp", ":6379"),
)
Types ¶
type GobSerializer ¶
type GobSerializer struct{}
GobSerializer is a struct that provides methods for serializing and deserializing data using the Gob encoding format. Gob is a binary serialization format that is efficient and compact, making it suitable for encoding complex data structures in Go.
func (GobSerializer) Deserialize ¶
func (s GobSerializer) Deserialize(d []byte, ss *sessions.Session) error
Deserialize decodes the given byte slice into the session's Values field. It uses the gob package to perform the decoding.
Parameters:
d - The byte slice to be deserialized. ss - The session object where the deserialized data will be stored.
Returns:
An error if the deserialization fails, otherwise nil.
func (GobSerializer) Serialize ¶
func (s GobSerializer) Serialize(ss *sessions.Session) ([]byte, error)
Serialize encodes the session values using gob encoding and returns the serialized byte slice. If the encoding process encounters an error, it returns nil and the error.
Parameters:
ss - A pointer to the session to be serialized.
Returns:
A byte slice containing the serialized session values, or nil if an error occurred during encoding. The error encountered during encoding is also returned.
type JSONSerializer ¶
type JSONSerializer struct{}
JSONSerializer is a struct that provides methods for serializing and deserializing data to and from JSON format. It can be used to convert Go data structures into JSON strings and vice versa.
func (JSONSerializer) Deserialize ¶
func (s JSONSerializer) Deserialize(d []byte, ss *sessions.Session) error
Deserialize takes a byte slice and a pointer to a sessions.Session, and attempts to deserialize the byte slice into the session's Values map. It returns an error if the deserialization process fails.
Parameters: - d: A byte slice containing the serialized session data. - ss: A pointer to the sessions.Session where the deserialized data will be stored.
Returns: - An error if the deserialization process fails, otherwise nil.
func (JSONSerializer) Serialize ¶
func (s JSONSerializer) Serialize(ss *sessions.Session) ([]byte, error)
Serialize converts the session's values into a JSON-encoded byte slice. It returns an error if any of the session keys are not strings.
Parameters:
ss - A pointer to the session to be serialized.
Returns:
A byte slice containing the JSON-encoded session values, or an error if serialization fails.
type Option ¶
type Option func(*storeConfig) error
Option is a function type for configuring a RediStore.
func WithAddress ¶
WithAddress configures the RediStore to connect to Redis using network and address. This option is mutually exclusive with WithPool and WithURL.
Example:
WithAddress("tcp", "localhost:6379")
WithAddress("unix", "/tmp/redis.sock")
func WithAuth ¶
WithAuth sets the username and password for Redis authentication. Both username and password can be empty strings if not required.
func WithDB ¶
WithDB sets the Redis database index to use. The db parameter should be a string representation of a number between 0 and 15. If empty, defaults to "0".
func WithDBNum ¶
WithDBNum sets the Redis database index using an integer. This is a convenience function equivalent to WithDB(strconv.Itoa(dbNum)).
func WithDefaultMaxAge ¶
WithDefaultMaxAge sets the default TTL (time-to-live) in seconds for sessions. This is used when session.Options.MaxAge is 0. Default is 1200 seconds (20 minutes).
func WithIdleTimeout ¶
WithIdleTimeout sets the idle timeout for connections in the pool. Default is 240 seconds. Only applies when using WithAddress or WithURL.
func WithKeyPrefix ¶
WithKeyPrefix sets the prefix for all Redis keys used by this store. Default is "session_". This is useful to avoid key collisions when using a single Redis instance for multiple applications.
func WithMaxAge ¶
WithMaxAge sets the MaxAge for session cookies in seconds. Default is sessionExpire (86400 * 30 = 30 days). This is a convenience function that modifies session options.
func WithMaxLength ¶
WithMaxLength sets the maximum size of session data in bytes. Default is 4096 bytes. Set to 0 for no limit (use with caution). Redis allows values up to 512MB.
func WithPassword ¶
WithPassword sets only the password for Redis authentication. This is a convenience function for Redis instances that don't use username.
func WithPath ¶
WithPath sets the cookie path for sessions. Default is "/". This is a convenience function that modifies session options.
func WithPool ¶
WithPool configures the RediStore to use a custom Redis connection pool. This option is mutually exclusive with WithAddress and WithURL.
func WithPoolSize ¶
WithPoolSize sets the maximum number of idle connections in the pool. Default is 10. Only applies when using WithAddress or WithURL.
func WithSerializer ¶
func WithSerializer(serializer SessionSerializer) Option
WithSerializer sets the session serializer. Default is GobSerializer. You can also use JSONSerializer or implement your own SessionSerializer.
func WithSessionOptions ¶
WithSessionOptions sets the default session options. This allows fine-grained control over cookie behavior.
type RediStore ¶
type RediStore struct {
Pool *redis.Pool
Codecs []securecookie.Codec
Options *sessions.Options // default configuration
DefaultMaxAge int // default Redis TTL for a MaxAge == 0 session
// contains filtered or unexported fields
}
RediStore represents a session store backed by a Redis database. It provides methods to manage session data using Redis as the storage backend.
Fields:
Pool: A connection pool for Redis. Codecs: A list of securecookie.Codec used to encode and decode session data. Options: Default configuration options for sessions. DefaultMaxAge: Default TTL (Time To Live) for sessions with MaxAge == 0. maxLength: Maximum length of session data. keyPrefix: Prefix to be added to all Redis keys used by this store. serializer: Serializer used to encode and decode session data.
Example ¶
// RedisStore
store, err := NewStore(
[][]byte{[]byte("secret-key")},
WithAddress("tcp", ":6379"),
WithPoolSize(10),
)
if err != nil {
panic(err)
}
defer func() {
if err := store.Close(); err != nil {
fmt.Printf("Error closing store: %v\n", err)
}
}()
func NewStore ¶
NewStore creates a new RediStore with the given options.
Parameters:
keyPairs - One or more key pairs for cookie encryption and authentication.
Each key should be 16, 24, or 32 bytes for AES-128, AES-192, or AES-256.
Keys are used in pairs: authentication key and encryption key.
Provide multiple pairs for key rotation (first pair is used for encoding,
remaining pairs are used for decoding only).
opts - Configuration options. At least one connection option is required.
Connection Options (required, exactly one):
- WithPool(pool) - Use a custom Redis connection pool
- WithAddress(network, address) - Connect using network protocol and address
- WithURL(url) - Connect using a Redis URL
Authentication Options:
- WithAuth(username, password) - Set username and password
- WithPassword(password) - Set password only
Redis Configuration Options:
- WithDB(db) - Set database index (default "0")
- WithDBNum(n) - Set database index as integer
- WithPoolSize(size) - Set connection pool size (default 10)
- WithIdleTimeout(timeout) - Set idle timeout (default 240s)
Store Configuration Options:
- WithMaxLength(length) - Set max session size (default 4096)
- WithKeyPrefix(prefix) - Set Redis key prefix (default "session_")
- WithDefaultMaxAge(age) - Set default TTL (default 1200)
- WithSerializer(s) - Set serializer (default GobSerializer)
- WithSessionOptions(opts) - Set session options
- WithPath(path) - Set cookie path (default "/")
- WithMaxAge(age) - Set cookie MaxAge (default 30 days)
Example:
// Basic usage with single key (using helper function)
store, err := NewStore(
KeysFromStrings("secret-key"),
WithAddress("tcp", ":6379"),
)
// Using Keys() with byte slices
store, err := NewStore(
Keys(
[]byte("authentication-key"), // 32 or 64 bytes
[]byte("encryption-key"), // 16, 24, or 32 bytes
),
WithAddress("tcp", ":6379"),
)
// With key rotation (old keys for decoding only)
store, err := NewStore(
KeysFromStrings(
"new-auth-key",
"new-encrypt-key",
"old-auth-key", // For decoding existing sessions
"old-encrypt-key",
),
WithAddress("tcp", "localhost:6379"),
WithDB("1"),
)
// With multiple options
store, err := NewStore(
KeysFromStrings("secret-key"),
WithAddress("tcp", "localhost:6379"),
WithDB("1"),
WithMaxLength(8192),
WithKeyPrefix("myapp_"),
WithSerializer(JSONSerializer{}),
)
// Using URL
store, err := NewStore(
KeysFromStrings("secret-key"),
WithURL("redis://:password@localhost:6379/0"),
)
// Without helper functions (direct slice)
store, err := NewStore(
[][]byte{[]byte("secret-key")},
WithAddress("tcp", ":6379"),
)
func (*RediStore) Delete ¶
func (s *RediStore) Delete( r *http.Request, w http.ResponseWriter, session *sessions.Session, ) error
Delete removes the session from redis, and sets the cookie to expire.
WARNING: This method should be considered deprecated since it is not exposed via the gorilla/sessions interface. Set session.Options.MaxAge = -1 and call Save instead. - July 18th, 2013
func (*RediStore) Get ¶
Get returns a session for the given name after adding it to the registry.
See gorilla/sessions FilesystemStore.Get().
func (*RediStore) New ¶
New returns a session for the given name without adding it to the registry.
See gorilla/sessions FilesystemStore.New().
func (*RediStore) SetKeyPrefix ¶
SetKeyPrefix sets the key prefix for all keys used in the RediStore. This is useful to avoid key name collisions when using a single Redis instance for multiple applications.
func (*RediStore) SetMaxAge ¶
SetMaxAge restricts the maximum age, in seconds, of the session record both in database and a browser. This is to change session storage configuration. If you want just to remove session use your session `s` object and change it's `Options.MaxAge` to -1, as specified in
http://godoc.org/github.com/gorilla/sessions#Options
Default is the one provided by this package value - `sessionExpire`. Set it to 0 for no restriction. Because we use `MaxAge` also in SecureCookie crypting algorithm you should use this function to change `MaxAge` value.
func (*RediStore) SetMaxLength ¶
SetMaxLength sets RediStore.maxLength if the `l` argument is greater or equal 0 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 RediStore is 4096. Redis allows for max. value sizes of up to 512MB (http://redis.io/topics/data-types) Default: 4096,
func (*RediStore) SetSerializer ¶
func (s *RediStore) SetSerializer(ss SessionSerializer)
SetSerializer sets the session serializer for the RediStore. The serializer is responsible for encoding and decoding session data.
Parameters:
ss - The session serializer to be used.
type SessionSerializer ¶
type SessionSerializer interface {
Deserialize(d []byte, ss *sessions.Session) error
Serialize(ss *sessions.Session) ([]byte, error)
}
SessionSerializer is an interface that defines methods for serializing and deserializing session data. Implementations of this interface should provide mechanisms to convert session data to and from byte slices.