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
python
from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException, status from pydantic import BaseModel, EmailStr from sqlalchemy.orm import Session
Building a signup endpoint in FastAPI
dependency-injection
request-validation
background-tasks
Intermediate
8 steps
javascript
const ROLE_PERMISSIONS = { admin: ['users:read', 'users:write', 'billing:read', 'billing:write'], manager: ['users:read', 'billing:read'], member: ['users:read'],
Role-based permissions middleware in Express
authorization
middleware
rbac
Intermediate
9 steps
go
package handlers import ( "net/http"
Serving embedded static meta files in Gin
embedding
static assets
http caching
Intermediate
6 steps
go
package config import ( "fmt"
A thread-safe config singleton in Go
singleton
concurrency
environment-variables
Intermediate
7 steps
javascript
const express = require('express'); const app = express(); app.get('/health', (req, res) => res.json({ status: 'ok' }));
Graceful shutdown in an Express server
graceful-shutdown
signal-handling
connection-tracking
Advanced
9 steps
php
<?php namespace App\Http\Middleware;
Resolving the current team in Laravel middleware
middleware
multi-tenancy
cookies
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.