go
54 lines · 7 steps
Role-based access control middleware in Gin
A Gin middleware factory that gates handlers behind required roles pulled from request-scoped claims.
Explained by
highlit
1package middleware
2
3import (
4 "net/http"
5
6 "github.com/gin-gonic/gin"
7)
8
9type Claims struct {
10 UserID string
11 Email string
12 Roles []string
13}
14
15func (c Claims) HasRole(role string) bool {
16 for _, r := range c.Roles {
17 if r == role {
18 return true
19 }
20 }
21 return false
22}
23
24func RequireRole(roles ...string) gin.HandlerFunc {
25 return func(c *gin.Context) {
26 val, exists := c.Get("claims")
27 if !exists {
28 c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{
29 "error": "authentication required",
30 })
31 return
32 }
33
34 claims, ok := val.(Claims)
35 if !ok {
36 c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{
37 "error": "invalid claims context",
38 })
39 return
40 }
41
42 for _, role := range roles {
43 if claims.HasRole(role) {
44 c.Next()
45 return
46 }
47 }
48
49 c.AbortWithStatusJSON(http.StatusForbidden, gin.H{
50 "error": "insufficient permissions",
51 "required": roles,
52 })
53 }
54}
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Returning a closure from a factory lets you configure middleware with parameters like allowed roles.
- 2Distinguishing missing context (401), bad type (500), and lack of permission (403) gives callers precise failure signals.
- 3Storing typed claims in the request context decouples authentication from per-route authorization checks.
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
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 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
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/role-based-access-control-middleware-in-gin-explained-go-dd85/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.