To create and use secure session tokens in Go, you can follow these steps:
import (
"crypto/rand"
"encoding/base64"
"net/http"
"time"
)
type Session struct {
ID string
Data map[string]interface{}
ExpiryTime time.Time
}
func generateRandomString(n int) (string, error) {
bytes := make([]byte, n)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return base64.URLEncoding.EncodeToString(bytes), nil
}
func createSession(w http.ResponseWriter, r *http.Request) (*Session, error) {
sessionID, err := generateRandomString(32)
if err != nil {
return nil, err
}
session := &Session{
ID: sessionID,
Data: make(map[string]interface{}),
ExpiryTime: time.Now().Add(24 * time.Hour), // Set the session expiry time (e.g., 24 hours)
}
// Store the session ID in a cookie
cookie := http.Cookie{
Name: "session",
Value: sessionID,
Expires: session.ExpiryTime,
HttpOnly: true, // Prevent JavaScript access to the cookie
}
http.SetCookie(w, &cookie)
// Save the session in a database or cache
// You can use a key-value store or a database to store session data
return session, nil
}
func getSession(r *http.Request) (*Session, error) {
cookie, err := r.Cookie("session")
if err != nil {
return nil, err
}
sessionID := cookie.Value
// Retrieve the session from the database or cache
// Load the session data associated with the session ID
return session, nil
}
func exampleHandler(w http.ResponseWriter, r *http.Request) {
session, err := getSession(r)
if err != nil {
// Handle error (e.g., redirect to login page)
return
}
session.Data["key"] = "value"
// Save or update the session in the database or cache
}
func main() {
http.HandleFunc("/", exampleHandler)
// Set up your other routes and handlers
http.ListenAndServe(":8080", nil)
}
Remember to use secure transport (HTTPS) to transmit session cookies to ensure the security of your session tokens.