redistore

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Mar 30, 2025 License: MIT Imports: 13 Imported by: 228

README

redistore

codecov Go Report Card GoDoc Run Tests

A session store backend for gorilla/sessions - src.

Requirements

Depends on the Redigo Redis library.

Installation

go get github.com/boj/redistore

Documentation

Available on godoc.org.

See the repository for full documentation on underlying interface.

Example
package main

import (
  "log"
  "net/http"

  "github.com/boj/redistore"
  "github.com/gorilla/sessions"
)

func main() {
  // Fetch new store.
  store, err := redistore.NewRediStore(10, "tcp", ":6379", "", "", []byte("secret-key"))
  if err != nil {
    panic(err)
  }
  defer store.Close()

  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    // Get a session.
    session, err := store.Get(r, "session-key")
    if err != nil {
      log.Println(err.Error())
      return
    }

    // Add a value.
    session.Values["foo"] = "bar"

    // Save.
    if err = sessions.Save(r, w); err != nil {
      log.Fatalf("Error saving session: %v", err)
    }

    // Delete session.
    session.Options.MaxAge = -1
    if err = sessions.Save(r, w); err != nil {
      log.Fatalf("Error saving session: %v", err)
    }
  })

  log.Fatal(http.ListenAndServe(":8080", nil))
}

Configuration

SetMaxLength

Sets the maximum length of new sessions. If the length is 0, there is no limit to the size of a session.

store.SetMaxLength(4096)
SetKeyPrefix

Sets the prefix for session keys in Redis.

store.SetKeyPrefix("myprefix_")
SetSerializer

Sets the serializer for session data. The default is GobSerializer.

store.SetSerializer(redistore.JSONSerializer{})
SetMaxAge

Sets the maximum age, in seconds, of the session record both in the database and in the browser.

store.SetMaxAge(86400 * 7) // 7 days

Custom Serializers

JSONSerializer

Serializes session data to JSON.

type JSONSerializer struct{}

func (s JSONSerializer) Serialize(ss *sessions.Session) ([]byte, error) {
  // Implementation
}

func (s JSONSerializer) Deserialize(d []byte, ss *sessions.Session) error {
  // Implementation
}
GobSerializer

Serializes session data using the gob package.

type GobSerializer struct{}

func (s GobSerializer) Serialize(ss *sessions.Session) ([]byte, error) {
  // Implementation
}

func (s GobSerializer) Deserialize(d []byte, ss *sessions.Session) error {
  // Implementation
}

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package redistore is a session store backend for gorilla/sessions

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

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 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 := NewRediStore(10, "tcp", ":6379", "", "", []byte("secret-key"))
if err != nil {
	panic(err)
}
defer func() {
	if err := store.Close(); err != nil {
		fmt.Printf("Error closing store: %v\n", err)
	}
}()
Output:

func NewRediStore

func NewRediStore(size int, network, address, username, password string, keyPairs ...[]byte) (*RediStore, error)

NewRediStore creates a new RediStore with a connection pool to a Redis server. The size parameter specifies the maximum number of idle connections in the pool. The network and address parameters specify the network type and address of the Redis server. The username and password parameters are used for authentication with the Redis server. The keyPairs parameter is a variadic argument that allows passing multiple key pairs for cookie encryption. It returns a pointer to a RediStore and an error if the connection to the Redis server fails.

func NewRediStoreWithDB

func NewRediStoreWithDB(size int, network, address, username, password, DB string, keyPairs ...[]byte) (*RediStore, error)

NewRediStoreWithDB creates a new RediStore with a Redis connection pool. The pool is configured with the provided size, network, address, username, password, and database (DB). The keyPairs are used for cookie encryption.

Parameters:

  • size: The maximum number of idle connections in the pool.
  • network: The network type (e.g., "tcp").
  • address: The address of the Redis server.
  • username: The username for Redis authentication.
  • password: The password for Redis authentication.
  • DB: The Redis database to be selected after connecting.
  • keyPairs: Variadic parameter for cookie encryption keys.

Returns:

  • *RediStore: A pointer to the newly created RediStore.
  • error: An error if the RediStore could not be created.

func NewRediStoreWithPool

func NewRediStoreWithPool(pool *redis.Pool, keyPairs ...[]byte) (*RediStore, error)

NewRediStoreWithPool creates a new RediStore instance using the provided Redis connection pool and key pairs for secure cookie encoding.

Parameters:

  • pool: A Redis connection pool.
  • keyPairs: Variadic parameter for secure cookie encoding key pairs.

Returns:

  • *RediStore: A pointer to the newly created RediStore instance.
  • error: An error if the RediStore could not be created.

The RediStore is configured with default options including a session path of "/", a default maximum age of 20 minutes, a maximum length of 4096 bytes, a key prefix of "session_", and a Gob serializer.

func NewRediStoreWithURL added in v1.4.0

func NewRediStoreWithURL(size int, url string, keyPairs ...[]byte) (*RediStore, error)

NewRediStoreWithURL creates a new RediStore with a Redis connection pool configured using the provided URL. The pool has a maximum number of idle connections specified by the size parameter, and an idle timeout of 240 seconds. The function also accepts optional key pairs for secure cookie encoding.

Parameters:

  • size: The maximum number of idle connections in the pool.
  • url: The Redis server URL.
  • keyPairs: Optional variadic parameter for secure cookie encoding.

Returns:

  • *RediStore: A pointer to the newly created RediStore.
  • error: An error if the connection to the Redis server fails.

func (*RediStore) Close

func (s *RediStore) Close() error

Close closes the underlying *redis.Pool

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

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

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

See gorilla/sessions FilesystemStore.Get().

func (*RediStore) New

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

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

See gorilla/sessions FilesystemStore.New().

func (*RediStore) Save

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

Save adds a single session to the response.

func (*RediStore) SetKeyPrefix

func (s *RediStore) SetKeyPrefix(p string)

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

func (s *RediStore) SetMaxAge(v int)

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

func (s *RediStore) SetMaxLength(l int)

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.

Jump to

Keyboard shortcuts

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