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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A factory function returning gin.HandlerFunc lets you configure middleware once and reuse the closure per request.
- 2Precomputing a normalized lookup set outside the handler keeps per-request work to a cheap map check.
- 3Skipping bodyless requests avoids rejecting legitimate GET and DELETE calls that carry no payload.
Related explainers
go
package streaming import ( "bufio"
Streaming NDJSON logs over HTTP in Go
http-streaming
channels
select
Advanced
10 steps
php
<?php namespace App\Services\Checkout;
Validating coupons with Laravel's Pipeline
pipeline
chain of responsibility
transactions
Intermediate
7 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
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
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/a-content-type-guard-middleware-in-gin-explained-go-e280/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.