go 39 lines · 7 steps

A content-type guard middleware in Gin

A Gin middleware factory that rejects requests whose Content-Type isn't in an allowed set.

Explained by highlit
1package middleware
2 
3import (
4 "net/http"
5 "strings"
6 
7 "github.com/gin-gonic/gin"
8)
9 
10func RequireContentType(allowed ...string) gin.HandlerFunc {
11 accepted := make(map[string]struct{}, len(allowed))
12 for _, ct := range allowed {
13 accepted[strings.ToLower(strings.TrimSpace(ct))] = struct{}{}
14 }
15 
16 return func(c *gin.Context) {
17 if c.Request.Method == http.MethodGet || c.Request.Method == http.MethodDelete {
18 c.Next()
19 return
20 }
21 
22 if c.Request.ContentLength == 0 {
23 c.Next()
24 return
25 }
26 
27 ct := strings.ToLower(c.ContentType())
28 if _, ok := accepted[ct]; !ok {
29 c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, gin.H{
30 "error": "unsupported content type",
31 "received": ct,
32 "expected": allowed,
33 })
34 return
35 }
36 
37 c.Next()
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A factory function returning gin.HandlerFunc lets you configure middleware once and reuse the closure per request.
  2. 2Precomputing a normalized lookup set outside the handler keeps per-request work to a cheap map check.
  3. 3Skipping bodyless requests avoids rejecting legitimate GET and DELETE calls that carry no payload.

Related explainers

Share this explainer

Here's the card — post it anywhere.

A content-type guard middleware in Gin — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code