Implement session-based authentication in Go by generating a random session ID, storing it in a server-side map, and setting it as a secure, HTTP-only cookie.
package main
import (
"crypto/rand"
"encoding/hex"
"net/http"
"time"
)
var sessions = make(map[string]bool)
func loginHandler(w http.ResponseWriter, r *http.Request) {
// Generate random session ID
b := make([]byte, 32)
rand.Read(b)
sessionID := hex.EncodeToString(b)
// Store session server-side
sessions[sessionID] = true
// Set secure, HTTP-only cookie
cookie := &http.Cookie{
Name: "session_id",
Value: sessionID,
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteLaxMode,
Expires: time.Now().Add(24 * time.Hour),
}
http.SetCookie(w, cookie)
w.Write([]byte("Logged in"))
}
func protectedHandler(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session_id")
if err != nil || !sessions[cookie.Value] {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
w.Write([]byte("Access granted"))
}
func main() {
http.HandleFunc("/login", loginHandler)
http.HandleFunc("/protected", protectedHandler)
http.ListenAndServe(":8080", nil)
}