redistore

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2025 License: MIT Imports: 14 Imported by: 0

README

redistore

codecov Go Report Card GoDoc Run Tests

A session store backend for gorilla/sessions - src.

Requirements

Depends on the Redis Universal Client library.

You can pass a list of Redis URL's to the store, and it will automatically handle the connection pooling for you. It does this by parsing the URL using redis.ParseURL(). See the Redis docs for more information.

OR if you already have a Redis client instance, you can create a new store using NewRediStoreWithExistingClient(). You can also create your own instance with advanced configurations, and pass that in here.

Installation

go get github.com/poseidonphp/redistore

Documentation

Available on godoc.org.

See the repository for full documentation on underlying interface.

Example
package main

import (
  "log"
  "net/http"

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

func main() {
  // Fetch new store.
  store, err := redistore.NewRediStore([]string{"redis://localhost:6379"}, false, []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.

About This Fork

This project is a fork of boj/redistore, originally created and maintained by Bojan Marković.

The original library uses the Redigo Redis client. This fork has been significantly modified to replace Redigo with the actively maintained go-redis (universal client).

Key changes:

  • Replaced Redigo with github.com/redis/go-redis/v9
  • Simplified connection handling using the UniversalClient abstraction
  • Dropped support for Redigo-based connection pooling

This fork is published under the same MIT License as the original and preserves all original licensing and attribution requirements.

If you're looking for the Redigo-based version, please refer to the original repository.

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 {
	Client        redis.UniversalClient
	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
addr := setup()
store, err := NewRediStore([]string{addr}, false, []byte("secret-key"))
if err != nil {
	panic(err)
}
defer func() {
	if err := store.Close(); err != nil {
		fmt.Printf("Error closing store: %v\n", err)
	}
}()

func NewRediStore

func NewRediStore(redisURLs []string, useTLS bool, 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 NewRediStoreWithExistingClient

func NewRediStoreWithExistingClient(client redis.UniversalClient, 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 (*RediStore) Close

func (s *RediStore) Close() error

Close closes the underlying *redis.Pool

func (*RediStore) Delete

func (s *RediStore) Delete(_ *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(_ *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