### Quick Start Implementation Source: https://github.com/boj/redistore/blob/master/README.md A complete example showing how to initialize the store and use it within an HTTP handler. ```go package main import ( "log" "net/http" "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) func main() { // Create a new store with options store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), ) 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 } // Set a value session.Values["foo"] = "bar" // Save session if err = sessions.Save(r, w); err != nil { log.Fatalf("Error saving session: %v", err) } }) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Main Server Setup Source: https://context7.com/boj/redistore/llms.txt Sets up the HTTP server, registers handlers for login, logout, profile, and health check endpoints, and starts the server on port 8080. Ensures the session store is closed upon application exit. ```go func main() { defer store.Close() http.HandleFunc("/login", loginHandler) http.HandleFunc("/logout", logoutHandler) http.HandleFunc("/profile", requireAuth(profileHandler)) http.HandleFunc("/health", healthHandler) log.Println("Server starting on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Complete Redistore Example with Custom Configuration Source: https://github.com/boj/redistore/blob/master/README.md A full example demonstrating how to initialize redistore with various custom configurations, including keys, address, database, max length, key prefix, and default max age, and setting up HTTP handlers for session management. ```go package main import ( "log" "net/http" "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) func main() { // Initialize store with custom configuration store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key-123"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithDB("1"), redistore.WithMaxLength(8192), redistore.WithKeyPrefix("webapp_"), redistore.WithDefaultMaxAge(3600), // 1 hour ) if err != nil { log.Fatal(err) } defer store.Close() http.HandleFunc("/set", func(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "my-session") session.Values["user"] = "john_doe" session.Values["authenticated"] = true sessions.Save(r, w) w.Write([]byte("Session saved!")) }) http.HandleFunc("/get", func(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "my-session") user := session.Values["user"] if user != nil { w.Write([]byte("User: " + user.(string))) } else { w.Write([]byte("No user in session")) } }) http.HandleFunc("/delete", func(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "my-session") session.Options.MaxAge = -1 sessions.Save(r, w) w.Write([]byte("Session deleted!")) }) log.Println("Server started on :8080") log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### v2 Complete Migration Example Source: https://github.com/boj/redistore/blob/master/MIGRATION.md A full example of initializing and configuring a redistore session in v2, including closing the store. ```go package main import ( "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) func main() { store, err := redistore.NewStore( []byte("secret-key-123"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithAuth("user", "password"), redistore.WithDB("1"), redistore.WithMaxLength(8192), redistore.WithKeyPrefix("myapp_"), redistore.WithMaxAge(86400 * 7), // 7 days ) if err != nil { panic(err) } defer store.Close() // Use store... } ``` -------------------------------- ### v1 Complete Migration Example Source: https://github.com/boj/redistore/blob/master/MIGRATION.md A full example of initializing and configuring a redistore session in v1, including closing the store. ```go package main import ( "github.com/boj/redistore" "github.com/gorilla/sessions" ) func main() { store, err := redistore.NewRediStoreWithDB( 10, "tcp", "localhost:6379", "user", "password", "1", []byte("secret-key-123"), ) if err != nil { panic(err) } defer store.Close() // Configure after creation store.SetMaxLength(8192) store.SetKeyPrefix("myapp_") store.SetMaxAge(86400 * 7) // 7 days // Use store... } ``` -------------------------------- ### v1 Connection using Redis URL Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Example of initializing a store using a Redis URL in v1. ```go store, err := redistore.NewRediStoreWithURL( 10, "redis://:password@localhost:6379/0", []byte("secret-key"), ) ``` -------------------------------- ### v1 Basic Connection Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Example of establishing a basic connection using redistore v1. ```go store, err := redistore.NewRediStore( 10, // pool size "tcp", // network ":6379", // address "", // username "", // password []byte("secret-key"), ) ``` -------------------------------- ### v1 Connection with Authentication Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Example of connecting with username and password in redistore v1. ```go store, err := redistore.NewRediStore( 10, "tcp", ":6379", "myuser", // username "mypass", // password []byte("secret-key"), ) ``` -------------------------------- ### Example Curl Command for Login Source: https://context7.com/boj/redistore/llms.txt An example command to test the login functionality using curl. It sends a POST request with username and password and saves the session cookies to 'cookies.txt'. ```bash # Login: curl -X POST -d "username=admin&password=password123" http://localhost:8080/login -c cookies.txt ``` -------------------------------- ### Install redistore Source: https://github.com/boj/redistore/blob/master/README.md Commands to install the current or legacy version of the library. ```sh go get github.com/boj/redistore/v2 ``` ```sh go get github.com/boj/redistore@v1 ``` -------------------------------- ### Handle Configuration Errors Source: https://github.com/boj/redistore/blob/master/README.md Example of how to catch and handle errors during RediStore initialization, specifically when multiple conflicting connection options are provided. ```go store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, redistore.WithAddress("tcp", ":6379"), redistore.WithURL("redis://localhost"), // ❌ Error: multiple connection options ) if err != nil { // Error: "only one connection option can be specified" log.Fatal(err) } ``` -------------------------------- ### Retrieve and Manage Sessions Source: https://context7.com/boj/redistore/llms.txt Use the Get method to retrieve or create a session. Remember to call sessions.Save to persist changes to the store. ```go package main import ( "encoding/json" "log" "net/http" "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) var store *redistore.RediStore func init() { var err error store, err = redistore.NewStore( redistore.KeysFromStrings("secret-key-32-bytes-long!!!!!!"), redistore.WithAddress("tcp", "localhost:6379"), ) if err != nil { log.Fatal(err) } } func handler(w http.ResponseWriter, r *http.Request) { // Get session (creates new if doesn't exist) session, err := store.Get(r, "user-session") if err != nil { http.Error(w, "Failed to get session: "+err.Error(), http.StatusInternalServerError) return } // Check if this is a new session if session.IsNew { log.Println("New session created") session.Values["visits"] = 0 } // Increment visit counter visits := session.Values["visits"].(int) visits++ session.Values["visits"] = visits // Save session if err := sessions.Save(r, w); err != nil { http.Error(w, "Failed to save session: "+err.Error(), http.StatusInternalServerError) return } // Return response json.NewEncoder(w).Encode(map[string]interface{}{ "visits": visits, "sessionID": session.ID, "isNew": session.IsNew, }) } func main() { defer store.Close() http.HandleFunc("/", handler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Run RediStore Tests Source: https://github.com/boj/redistore/blob/master/README.md Commands to start a Redis server and run the RediStore test suite, including options for generating code coverage reports. ```bash # Start Redis (required) redis-server # Run tests go test -v # With coverage go test -v -coverprofile=coverage.out go tool cover -html=coverage.out ``` -------------------------------- ### v1 Specific Database Connection Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Example of connecting to a specific Redis database using NewRediStoreWithDB in v1. ```go store, err := redistore.NewRediStoreWithDB( 10, "tcp", ":6379", "", "", "5", // database []byte("secret-key"), ) ``` -------------------------------- ### Login Handler Source: https://context7.com/boj/redistore/llms.txt Handles user login requests. It validates credentials (simplified for example), sets session values like authentication status, user ID, username, login time, and IP address, and saves the session. Requires a POST request with 'username' and 'password' form values. ```go func loginHandler(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return } username := r.FormValue("username") password := r.FormValue("password") // Validate credentials (simplified - use proper auth in production) if username != "admin" || password != "password123" { http.Error(w, "Invalid credentials", http.StatusUnauthorized) return } session, _ := store.Get(r, sessionName) // Set session values session.Values["authenticated"] = true session.Values["user_id"] = 1 session.Values["username"] = username session.Values["login_time"] = time.Now().Unix() session.Values["ip_address"] = r.RemoteAddr // Save session if err := sessions.Save(r, w); err != nil { http.Error(w, "Failed to save session", http.StatusInternalServerError) return } json.NewEncoder(w).Encode(map[string]interface{}{ "status": "success", "message": "Logged in successfully", }) } ``` -------------------------------- ### Generate Secure Random Keys for Redistore Source: https://context7.com/boj/redistore/llms.txt Generate cryptographically secure random keys for initial setup. Use these keys to initialize your redistore instance, and then store them securely. ```go newAuthKey := make([]byte, 32) newEncKey := make([]byte, 16) rand.Read(newAuthKey) rand.Read(newEncKey) log.Printf("New Auth Key: %s", hex.EncodeToString(newAuthKey)) log.Printf("New Encrypt Key: %s", hex.EncodeToString(newEncKey)) ``` -------------------------------- ### v2 Key Pairs Initialization with Helper Functions Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Demonstrates v2's recommended approach using KeysFromStrings for cleaner key pair management. ```go NewStore(KeysFromStrings("secret-key"), WithAddress("tcp", ":6379")) NewStore( KeysFromStrings( "auth-key", "encrypt-key", "old-auth-key", "old-encrypt-key", ), WithAddress("tcp", ":6379"), ) NewStore(Keys([]byte("secret-key")), WithAddress("tcp", ":6379")) NewStore([][]byte{[]byte("secret-key")}, WithAddress("tcp", ":6379")) ``` -------------------------------- ### v2 Basic Connection with Option Pattern Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Demonstrates establishing a basic connection in v2 using the NewStore function and options. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), // WithPoolSize is optional (defaults to 10) ) ``` -------------------------------- ### v2 Connection with Authentication Options Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Shows how to configure authentication using WithAuth and WithPassword options in v2. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), redistore.WithAuth("myuser", "mypass"), ) // Or just password: store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), redistore.WithPassword("mypass"), ) ``` -------------------------------- ### v1 Key Pairs Initialization Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Illustrates how key pairs were handled in v1 using variadic byte slices. ```go NewRediStore(10, "tcp", ":6379", "", "", []byte("secret-key")) NewRediStore(10, "tcp", ":6379", "", "", []byte("auth-key"), []byte("encrypt-key"), []byte("old-auth-key"), []byte("old-encrypt-key")) ``` -------------------------------- ### Connection Options Reference Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Lists available options for establishing a connection to Redis. ```go WithPool(pool *redis.Pool) // Use custom pool WithAddress(network, address string) // Connect via network + address WithURL(url string) // Connect via Redis URL ``` -------------------------------- ### v2 Specific Database Connection Options Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Demonstrates connecting to a specific database in v2 using WithDB and WithDBNum options. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), redistore.WithDB("5"), ) // Or using integer: store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), redistore.WithDBNum(5), ) ``` -------------------------------- ### Initialize Redistore with Key Rotation (Strings) Source: https://github.com/boj/redistore/blob/master/README.md Use KeysFromStrings to initialize the store with new and old keys for session encryption. The first pair is used for new sessions, while all pairs are tried for decoding existing sessions. ```go // Keys are provided in pairs: authentication key, encryption key // The first pair is used for encoding new sessions // All pairs are tried for decoding existing sessions store, err := redistore.NewStore( redistore.KeysFromStrings( "new-authentication-key", // 32 or 64 bytes recommended "new-encryption-key", // 16, 24, or 32 bytes for AES "old-authentication-key", // Keep for existing sessions "old-encryption-key", // Keep for existing sessions ), redistore.WithAddress("tcp", "localhost:6379"), ) ``` -------------------------------- ### Store Configuration Options Reference Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Lists available options for configuring the session store itself. ```go WithMaxLength(length int) // Max session size (default: 4096) WithKeyPrefix(prefix string) // Redis key prefix (default: "session_") WithDefaultMaxAge(age int) // Default TTL in seconds (default: 1200) WithSerializer(s SessionSerializer) // Serializer (default: GobSerializer) WithSessionOptions(opts *sessions.Options) // Full session options WithPath(path string) // Cookie path (default: "/") WithMaxAge(age int) // Cookie MaxAge (default: 30 days) ``` -------------------------------- ### Get Session Values Source: https://github.com/boj/redistore/blob/master/README.md Retrieves values associated with specific keys from the session. Always check for nil and perform type assertions. ```go session, _ := store.Get(r, "session-key") username := session.Values["username"] if username != nil { fmt.Println(username.(string)) } ``` -------------------------------- ### v2 Custom Configuration (All at Once) Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Shows how to configure session parameters like MaxLength, KeyPrefix, and Serializer during redistore session creation in v2. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), redistore.WithMaxLength(8192), redistore.WithKeyPrefix("myapp_"), redistore.WithSerializer(redistore.JSONSerializer{}), ) ``` -------------------------------- ### Migrate from RediStore v1 to v2 Source: https://github.com/boj/redistore/blob/master/README.md Compares the initialization syntax between RediStore v1 and v2, highlighting the shift towards the Option Pattern in v2. ```go // v1 store, err := redistore.NewRediStore(10, "tcp", ":6379", "", "", []byte("key")) // v2 store, err := redistore.NewStore( []byte("key"), redistore.WithAddress("tcp", ":6379"), ) ``` -------------------------------- ### Create Key Pairs with Helper Functions Source: https://github.com/boj/redistore/blob/master/CHANGELOG.md Use helper functions to simplify the creation of key pairs for the NewStore constructor. ```go store, err := NewStore(Keys([]byte("key")), WithAddress("tcp", ":6379")) ``` ```go store, err := NewStore(KeysFromStrings("secret-key"), WithAddress("tcp", ":6379")) ``` -------------------------------- ### Health Check Handler Source: https://context7.com/boj/redistore/llms.txt Checks the health of the Redis connection by attempting to get and save a session. Returns 'healthy' if successful, or 'unhealthy' with an error message if Redis is not accessible. ```go func healthHandler(w http.ResponseWriter, r *http.Request) { // Test Redis connection via session store session, err := store.Get(r, "health-check") if err != nil { w.WriteHeader(http.StatusServiceUnavailable) json.NewEncoder(w).Encode(map[string]string{"status": "unhealthy", "error": err.Error()}) return } session.Values["check"] = time.Now().Unix() if err := sessions.Save(r, w); err != nil { w.WriteHeader(http.StatusServiceUnavailable) json.NewEncoder(w).Encode(map[string]string{"status": "unhealthy", "error": err.Error()}) return } json.NewEncoder(w).Encode(map[string]string{"status": "healthy"}) } ``` -------------------------------- ### v1 Custom Configuration (Post-Creation) Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Demonstrates setting session parameters like MaxLength, KeyPrefix, and Serializer after creating a redistore session in v1. ```go store, err := redistore.NewRediStore(10, "tcp", ":6379", "", "", []byte("secret-key")) store.SetMaxLength(8192) store.SetKeyPrefix("myapp_") store.SetSerializer(redistore.JSONSerializer{}) ``` -------------------------------- ### Redistore v2: Correct Connection Option Usage Source: https://github.com/boj/redistore/blob/master/MIGRATION.md To correctly initialize redistore, choose a single connection method like WithAddress. This ensures proper configuration and avoids connection errors. ```go // Choose ONE connection method store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), // ✅ Only one ) ``` -------------------------------- ### Pitfall: Empty Key Pairs Fix Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Demonstrates the correct way to provide key pairs when initializing a redistore session to avoid errors. ```go store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, // ✅ Provide key redistore.WithAddress("tcp", ":6379"), ) ``` -------------------------------- ### v2 Use Existing Pool Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Shows how to initialize a redistore session in v2 by providing an existing custom redis.Pool. ```go pool := &redis.Pool{ MaxIdle: 100, IdleTimeout: 5 * time.Minute, Dial: func() (redis.Conn, error) { return redis.Dial("tcp", ":6379") }, } store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, redistore.WithPool(pool), ) ``` -------------------------------- ### Authentication Options Reference Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Lists available options for Redis authentication. ```go WithAuth(username, password string) // Set both username and password WithPassword(password string) // Set password only ``` -------------------------------- ### Manage Redis Sessions with RediStore Source: https://context7.com/boj/redistore/llms.txt Demonstrates initializing a RediStore instance and handling login, update, and logout operations using standard HTTP handlers. ```go package main import ( "log" "net/http" "time" "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) var store *redistore.RediStore func init() { var err error store, err = redistore.NewStore( redistore.KeysFromStrings("secret-key-32-bytes-long!!!!!!"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithDefaultMaxAge(3600), // 1 hour default TTL ) if err != nil { log.Fatal(err) } } func loginHandler(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "auth-session") // Store user data in session session.Values["user_id"] = 12345 session.Values["username"] = "john_doe" session.Values["email"] = "john@example.com" session.Values["authenticated"] = true session.Values["login_time"] = time.Now().Unix() // Save session to Redis if err := sessions.Save(r, w); err != nil { http.Error(w, "Failed to save session", http.StatusInternalServerError) return } w.Write([]byte("Login successful")) } func updateHandler(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "auth-session") // Update session values session.Values["last_activity"] = time.Now().Unix() // Extend session expiry (optional) session.Options.MaxAge = 7200 // 2 hours // Save changes if err := sessions.Save(r, w); err != nil { http.Error(w, "Failed to update session", http.StatusInternalServerError) return } w.Write([]byte("Session updated")) } func logoutHandler(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "auth-session") // Mark session for deletion session.Options.MaxAge = -1 // Save (this deletes from Redis and expires cookie) if err := sessions.Save(r, w); err != nil { http.Error(w, "Failed to delete session", http.StatusInternalServerError) return } w.Write([]byte("Logged out successfully")) } func main() { defer store.Close() http.HandleFunc("/login", loginHandler) http.HandleFunc("/update", updateHandler) http.HandleFunc("/logout", logoutHandler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Implement Flash Messages in Go Source: https://context7.com/boj/redistore/llms.txt Demonstrates initializing a RediStore, adding flash messages, and retrieving them using the gorilla/sessions API. ```go package main import ( "html/template" "log" "net/http" "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) var store *redistore.RediStore var templates = template.Must(template.New("").Parse(` {{range .Flashes}}
{{.}}
{{end}}
`)) func init() { var err error store, err = redistore.NewStore( redistore.KeysFromStrings("secret-key-32-bytes-long!!!!!!"), redistore.WithAddress("tcp", "localhost:6379"), ) if err != nil { log.Fatal(err) } } func formHandler(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "flash-session") // Retrieve and clear flash messages flashes := session.Flashes() // Must save to clear flashes from session sessions.Save(r, w) templates.Execute(w, map[string]interface{}{ "Flashes": flashes, }) } func submitHandler(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "flash-session") data := r.FormValue("data") if data == "" { // Add error flash session.AddFlash("Error: Data cannot be empty") } else { // Add success flash session.AddFlash("Success: Data saved successfully!") // Add typed flash with custom key session.AddFlash("info", "notification") session.AddFlash("Your submission has been processed", "notification") } // Save session with flash messages sessions.Save(r, w) // Redirect back to form (PRG pattern) http.Redirect(w, r, "/", http.StatusSeeOther) } func notificationHandler(w http.ResponseWriter, r *http.Request) { session, _ := store.Get(r, "flash-session") // Get flashes by key notifications := session.Flashes("notification") generalFlashes := session.Flashes() // Default key sessions.Save(r, w) log.Printf("Notifications: %v", notifications) log.Printf("General flashes: %v", generalFlashes) } func main() { defer store.Close() http.HandleFunc("/", formHandler) http.HandleFunc("/submit", submitHandler) http.HandleFunc("/notifications", notificationHandler) log.Fatal(http.ListenAndServe(":8080", nil)) } ``` -------------------------------- ### Initialize RediStore with NewStore Source: https://github.com/boj/redistore/blob/master/CHANGELOG.md Use the unified NewStore function with various options to configure the session store. Supports both single and multiple keys for rotation. ```go // Single key store, err := NewStore( [][]byte{[]byte("secret-key")}, WithAddress("tcp", ":6379"), WithDB("1"), WithMaxLength(8192), ) // Multiple keys for key rotation store, err := NewStore( [][]byte{ []byte("new-auth-key"), []byte("new-encrypt-key"), []byte("old-auth-key"), // For decoding existing sessions []byte("old-encrypt-key"), }, WithAddress("tcp", ":6379"), ) ``` -------------------------------- ### Initialize Redistore with Key Rotation (Byte Slices) Source: https://github.com/boj/redistore/blob/master/README.md Use Keys with byte slices for production environments, loading keys from a secure storage. This method is recommended for managing sensitive keys. ```go // Using Keys() with byte slices for production authKey, _ := loadKeyFromSecureStorage("auth-key") encryptKey, _ := loadKeyFromSecureStorage("encrypt-key") store, err := redistore.NewStore( redistore.Keys(authKey, encryptKey), redistore.WithAddress("tcp", "localhost:6379"), ) ``` -------------------------------- ### Initialize RediStore with NewStore Source: https://context7.com/boj/redistore/llms.txt Initializes a new session store using various connection methods like address, URL, or advanced configuration options. Requires at least one connection option such as WithPool, WithAddress, or WithURL. ```go package main import ( "log" "net/http" "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) func main() { // Basic initialization with address connection store, err := redistore.NewStore( redistore.KeysFromStrings("my-secret-key-32-bytes-long!!!!!"), redistore.WithAddress("tcp", "localhost:6379"), ) if err != nil { log.Fatal(err) } defer store.Close() // Full configuration example storeAdvanced, err := redistore.NewStore( redistore.KeysFromStrings( "new-auth-key-32-bytes-long!!!!!", "new-encrypt-key-16-bytes", "old-auth-key-32-bytes-long!!!!!", // For decoding existing sessions "old-encrypt-key-16-bytes", ), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithAuth("redis-user", "redis-password"), redistore.WithDB("1"), redistore.WithPoolSize(20), redistore.WithIdleTimeout(300*time.Second), redistore.WithMaxLength(8192), redistore.WithKeyPrefix("myapp_session_"), redistore.WithDefaultMaxAge(3600), redistore.WithSerializer(redistore.JSONSerializer{}), redistore.WithPath("/"), redistore.WithMaxAge(86400*7), // 7 days ) if err != nil { log.Fatal(err) } defer storeAdvanced.Close() // Using Redis URL storeURL, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithURL("redis://:password@localhost:6379/0"), ) if err != nil { log.Fatal(err) } defer storeURL.Close() } ``` -------------------------------- ### v2 Configure Pool Parameters Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Illustrates configuring connection pool parameters directly during redistore session creation in v2. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), redistore.WithPoolSize(100), redistore.WithIdleTimeout(5 * time.Minute), ) ``` -------------------------------- ### v2 Connection using Redis URL Option Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Shows how to connect using a Redis URL in v2 via the WithURL option. ```go store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, redistore.WithURL("redis://:password@localhost:6379/0"), ) ``` -------------------------------- ### Redis Configuration Options Reference Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Lists available options for configuring Redis connection pool and database. ```go WithDB(db string) // Database index as string ("0"-"15") WithDBNum(dbNum int) // Database index as integer (0-15) WithPoolSize(size int) // Connection pool size (default: 10) WithIdleTimeout(timeout time.Duration) // Idle timeout (default: 240s) ``` -------------------------------- ### Initialize RediStore Session Store Source: https://context7.com/boj/redistore/llms.txt Sets up the RediStore with custom configurations including secret keys, Redis address, database, key prefix, and session/cookie age limits. It also specifies JSON serialization for session data. Ensure Redis is running and accessible at the specified address. ```go package main import ( "encoding/json" "log" "net/http" "time" "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) var store *redistore.RediStore const sessionName = "app-session" func init() { var err error store, err = redistore.NewStore( redistore.KeysFromStrings("super-secret-key-32-bytes!!!!!"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithDB("0"), redistore.WithKeyPrefix("webapp_"), redistore.WithDefaultMaxAge(3600), // 1 hour session redistore.WithMaxAge(86400 * 7), // 7 day cookie redistore.WithMaxLength(4096), redistore.WithSerializer(redistore.JSONSerializer{}), ) if err != nil { log.Fatal("Failed to create session store:", err) } } ``` -------------------------------- ### Configure Redistore Store Options After Creation Source: https://context7.com/boj/redistore/llms.txt Shows how to modify redistore's configuration after initialization using methods like SetMaxLength, SetKeyPrefix, SetSerializer, and SetMaxAge. These methods mirror the With* options available during creation. ```go package main import ( "log" "github.com/boj/redistore/v2" ) func main() { // Create store with minimal options store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", "localhost:6379"), ) if err != nil { log.Fatal(err) } defer store.Close() // SetMaxLength - Set maximum session data size in bytes // Default: 4096, Set to 0 for unlimited (use with caution) store.SetMaxLength(8192) // 8KB max session size store.SetMaxLength(0) // Unlimited (up to Redis 512MB limit) // SetKeyPrefix - Set Redis key prefix for session storage // Default: "session_" // Useful for multi-tenant apps or separating environments store.SetKeyPrefix("myapp_prod_session_") store.SetKeyPrefix("tenant_123_") // SetSerializer - Change serialization format // Default: GobSerializer store.SetSerializer(redistore.JSONSerializer{}) store.SetSerializer(redistore.GobSerializer{}) // Switch back // SetMaxAge - Set session cookie and Redis TTL in seconds // Default: 86400 * 30 (30 days) // Also updates SecureCookie's internal MaxAge for proper crypto store.SetMaxAge(3600) // 1 hour store.SetMaxAge(86400 * 7) // 7 days store.SetMaxAge(0) // Session cookie (expires when browser closes) log.Println("Store configured successfully") } ``` -------------------------------- ### Configure Session Serialization with Redistore Source: https://context7.com/boj/redistore/llms.txt Demonstrates initializing redistore with different serializers: GobSerializer (default), JSONSerializer, and a custom serializer. Includes registering custom types for GobSerializer. ```go package main import ( "bytes" "encoding/gob" "encoding/json" "log" "net/http" "github.com/boj/redistore/v2" "github.com/gorilla/sessions" ) // Custom serializer using msgpack (example) type CustomSerializer struct{} func (s CustomSerializer) Serialize(ss *sessions.Session) ([]byte, error) { // Convert to string-keyed map for JSON compatibility m := make(map[string]interface{}) for k, v := range ss.Values { if ks, ok := k.(string); ok { m[ks] = v } } return json.Marshal(m) // Replace with msgpack or other encoding } func (s CustomSerializer) Deserialize(d []byte, ss *sessions.Session) error { m := make(map[string]interface{}) if err := json.Unmarshal(d, &m); err != nil { return err } for k, v := range m { ss.Values[k] = v } return nil } func main() { // Using GobSerializer (default) - best for Go-only applications storeGob, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", "localhost:6379"), // GobSerializer is default, no need to specify ) if err != nil { log.Fatal(err) } defer storeGob.Close() // Using JSONSerializer - human-readable, cross-language compatible storeJSON, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithSerializer(redistore.JSONSerializer{}), ) if err != nil { log.Fatal(err) } defer storeJSON.Close() // Using custom serializer storeCustom, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithSerializer(CustomSerializer{}), ) if err != nil { log.Fatal(err) } defer storeCustom.Close() // Register custom types for GobSerializer gob.Register(map[string]interface{}{}) gob.Register([]interface{}{}) // Register your custom structs type User struct { ID int Name string Email string } gob.Register(User{}) http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { session, _ := storeGob.Get(r, "session") session.Values["user"] = User{ID: 1, Name: "John", Email: "john@example.com"} sessions.Save(r, w) w.Write([]byte("Session saved with custom type")) }) } ``` -------------------------------- ### Redistore v2: Multiple Connection Options Error Source: https://github.com/boj/redistore/blob/master/MIGRATION.md When initializing redistore, only one connection method (e.g., WithAddress or WithURL) can be specified. Attempting to use multiple will result in an error. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), // ❌ redistore.WithURL("redis://localhost"), // ❌ Multiple connections ) // Error: "only one connection option can be specified" ``` -------------------------------- ### Configure Redis Connection Source: https://github.com/boj/redistore/blob/master/README.md Various methods to initialize the store connection, including authentication, database selection, and URL strings. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", "localhost:6379"), ) ``` ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithAuth("username", "password"), ) ``` ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithDB("5"), // Use database 5 ) ``` ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithURL("redis://:password@localhost:6379/0"), ) ``` -------------------------------- ### Create Redistore with KeysFromStrings Source: https://context7.com/boj/redistore/llms.txt Use KeysFromStrings for simple key pair creation, suitable for development and testing. It accepts a single string for authentication or multiple strings for authentication and encryption keys. ```go store1, err := redistore.NewStore( redistore.KeysFromStrings("my-32-byte-authentication-key!!"), redistore.WithAddress("tcp", "localhost:6379"), ) if err != nil { log.Fatal(err) } defer store1.Close() ``` -------------------------------- ### Define and Use Custom Session Serializer Source: https://github.com/boj/redistore/blob/master/README.md Demonstrates how to implement a custom session serializer by adhering to the `SessionSerializer` interface and then using it with RediStore. ```go type SessionSerializer interface { Serialize(ss *sessions.Session) ([]byte, error) Deserialize(d []byte, ss *sessions.Session) error } type MySerializer struct{} func (s MySerializer) Serialize(ss *sessions.Session) ([]byte, error) { // Your implementation } func (s MySerializer) Deserialize(d []byte, ss *sessions.Session) error { // Your implementation } // Use it store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, redistore.WithAddress("tcp", ":6379"), redistore.WithSerializer(MySerializer{}), ) ``` -------------------------------- ### Store Configuration Options Source: https://github.com/boj/redistore/blob/master/README.md Configuration options available when initializing the RediStore. ```APIDOC ## Store Configuration ### Options | Option | Default | Description | | -------------------------- | ------------- | ----------------------------------------- | | `WithMaxLength(length)` | 4096 | Max session size in bytes (0 = unlimited) | | `WithKeyPrefix(prefix)` | "session_" | Redis key prefix | | `WithDefaultMaxAge(age)` | 1200 | Default TTL in seconds (20 minutes) | | `WithSerializer(s)` | GobSerializer | Session serializer | | `WithSessionOptions(opts)` | - | Full gorilla/sessions options | | `WithPath(path)` | "/" | Cookie path | | `WithMaxAge(age)` | 30 days | Cookie MaxAge | ``` -------------------------------- ### Post-Initialization Configuration Source: https://github.com/boj/redistore/blob/master/README.md Modifying store settings after the RediStore has been initialized. ```APIDOC ## Post-Initialization Configuration While the Option Pattern is recommended, you can still modify settings after creation: ```go store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, redistore.WithAddress("tcp", ":6379"), ) // Modify after creation store.SetMaxLength(16384) store.SetKeyPrefix("app2_") store.SetSerializer(redistore.JSONSerializer{}) store.SetMaxAge(86400 * 7) // 7 days ``` ``` -------------------------------- ### Testing Application After Migration Source: https://github.com/boj/redistore/blob/master/MIGRATION.md After migrating your application, run these commands to verify its functionality and ensure there are no compilation errors or runtime issues. ```bash # Run your tests go test ./... # Check for compilation errors go build ./... # Run your application in development go run main.go ``` -------------------------------- ### v1 Custom Connection Pool Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Demonstrates creating a redistore session using a pre-configured custom redis.Pool in v1. ```go pool := &redis.Pool{ MaxIdle: 100, IdleTimeout: 5 * time.Minute, Dial: func() (redis.Conn, error) { return redis.Dial("tcp", ":6379") }, } store, err := redistore.NewRediStoreWithPool(pool, []byte("secret-key")) ``` -------------------------------- ### Create Redistore with Keys (Byte Slices) Source: https://context7.com/boj/redistore/llms.txt Use Keys when you have authentication and encryption keys already available as byte slices. This method is useful for loading keys from secure storage. ```go authKey := []byte("my-32-byte-authentication-key!!") encryptKey := []byte("16-byte-encrypt!") // AES-128 store2, err := redistore.NewStore( redistore.Keys(authKey, encryptKey), redistore.WithAddress("tcp", "localhost:6379"), ) if err != nil { log.Fatal(err) } defer store2.Close() ``` -------------------------------- ### Advanced Store Configuration Source: https://github.com/boj/redistore/blob/master/README.md Customizing session behavior such as TTL, key prefixes, and serialization formats. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", "localhost:6379"), redistore.WithMaxLength(8192), // Max session size: 8KB redistore.WithKeyPrefix("myapp_"), // Key prefix redistore.WithDefaultMaxAge(3600), // Default TTL: 1 hour redistore.WithSerializer(redistore.JSONSerializer{}), // JSON serializer ) ``` -------------------------------- ### Serializer Options Source: https://github.com/boj/redistore/blob/master/README.md Demonstrates how to configure different serializers for RediStore. ```APIDOC ## Serializers ### Gob Serializer (Default) Uses Go's `encoding/gob` package. Efficient binary format, suitable for complex Go types. ```go store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, redistore.WithAddress("tcp", ":6379"), // GobSerializer is the default, no need to specify ) ``` ### JSON Serializer Uses `encoding/json` package. Human-readable, cross-language compatible. ```go store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, redistore.WithAddress("tcp", ":6379"), redistore.WithSerializer(redistore.JSONSerializer{}), ) ``` ### Custom Serializer Implement the `SessionSerializer` interface: ```go type SessionSerializer interface { Serialize(ss *sessions.Session) ([]byte, error) Deserialize(d []byte, ss *sessions.Session) error } type MySerializer struct{} func (s MySerializer) Serialize(ss *sessions.Session) ([]byte, error) { // Your implementation } func (s MySerializer) Deserialize(d []byte, ss *sessions.Session) error { // Your implementation } // Use it store, err := redistore.NewStore( [][]byte{[]byte("secret-key")}, redistore.WithAddress("tcp", ":6379"), redistore.WithSerializer(MySerializer{}), ) ``` ``` -------------------------------- ### Pitfall: No Connection Option Fix Source: https://github.com/boj/redistore/blob/master/MIGRATION.md Illustrates adding a connection option when initializing a redistore session to resolve the 'exactly one connection option is required' error. ```go store, err := redistore.NewStore( redistore.KeysFromStrings("secret-key"), redistore.WithAddress("tcp", ":6379"), // ✅ Add connection option redistore.WithMaxLength(8192), ) ```