go
53 lines · 7 steps
Cookie-based sessions in Gin
A login handler issues a signed session cookie, and a middleware verifies it on every protected request.
Explained by
highlit
1package handlers
2
3import (
4 "net/http"
5 "time"
6
7 "github.com/gin-gonic/gin"
8)
9
10const sessionCookie = "session_token"
11
12type SessionHandler struct {
13 Secret string
14 Secure bool
15}
16
17func (h *SessionHandler) Login(c *gin.Context) {
18 var req struct {
19 Email string `json:"email" binding:"required,email"`
20 Password string `json:"password" binding:"required"`
21 }
22 if err := c.ShouldBindJSON(&req); err != nil {
23 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
24 return
25 }
26
27 token, err := AuthenticateAndIssueToken(c.Request.Context(), req.Email, req.Password)
28 if err != nil {
29 c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
30 return
31 }
32
33 c.SetSameSite(http.SameSiteLaxMode)
34 c.SetCookie(sessionCookie, sign(token, h.Secret), int(24*time.Hour.Seconds()), "/", "", h.Secure, true)
35 c.JSON(http.StatusOK, gin.H{"status": "ok"})
36}
37
38func (h *SessionHandler) RequireSession(c *gin.Context) {
39 signed, err := c.Cookie(sessionCookie)
40 if err != nil {
41 c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing session"})
42 return
43 }
44
45 token, ok := verify(signed, h.Secret)
46 if !ok {
47 c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "tampered session"})
48 return
49 }
50
51 c.Set("sessionToken", token)
52 c.Next()
53}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Signing a cookie's value lets you trust it later without server-side session storage.
- 2Middleware that calls AbortWithStatusJSON stops the chain so unauthenticated requests never reach the handler.
- 3Setting HttpOnly and SameSite on the cookie defends sessions against XSS and CSRF leakage.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
python
import time import uuid from django.utils.deprecation import MiddlewareMixin
Attaching per-request context in Django
middleware
request lifecycle
multi-tenancy
Intermediate
7 steps
go
package api import ( "crypto/sha256"
ETag conditional requests in Gin
http-caching
etag
conditional-requests
Intermediate
6 steps
go
func (w *Watcher) resetDebounce(d time.Duration) { if !w.timer.Stop() { select { case <-w.timer.C:
Debouncing a stream of events in Go
debounce
timers
channels
Advanced
7 steps
go
package logging import ( "context"
Deduplicating log attributes in Go's slog
decorator-pattern
structured-logging
immutability
Intermediate
8 steps
ruby
class ApplicationController < ActionController::Base EXPERIMENTS = { checkout_button_color: %w[control blue green], onboarding_flow: %w[control streamlined]
How A/B test cohorts are assigned in Rails
a-b-testing
cookies
hashing
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/cookie-based-sessions-in-gin-explained-go-a92e/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.