Sessions - SQLite3
This example uses the SQLite3 storage package to persist user sessions. While the storage package can automatically create the sessions table at initialization, we create it manually to add an additional "u" column. This custom column serves several purposes:
- Enables efficient querying of sessions by user identifier
- Allows tracking of multiple sessions per user
- Facilitates session cleanup for specific users
The default table schema only stores session data and expiry, making it difficult to associate sessions with specific users. The "u" column solves this limitation.
Prerequisites
- Go 1.16 or higher
- Go modules
Setup
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git
cd recipes/sessions-sqlite3 -
Install dependencies:
go mod tidy
-
Create the sessions table in SQLite3:
CREATE TABLE sessions (
key TEXT PRIMARY KEY,
data BLOB,
expiry INTEGER,
u TEXT
);
Running the Application
-
Run the application:
go run main.go
-
The server will start on
http://localhost:3000
.
Explanation
This example uses the SQLite3 storage package to persist user sessions. The storage package can create the sessions table for you at initialization, but for the purpose of this example, the table is created manually with an additional "u" column to better query all user-related sessions.