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
javascript
const express = require('express'); const { createProxyMiddleware, fixRequestBody } = require('http-proxy-middleware'); const router = express.Router();
Building an API gateway proxy in Express
reverse-proxy
middleware
api-gateway
Intermediate
6 steps
go
package middleware import ( "net/http"
Per-IP write rate limiting in Gin
rate-limiting
middleware
concurrency
Intermediate
8 steps
python
import asyncio from dataclasses import dataclass import aiohttp
Bounded-concurrency HTTP fetching with asyncio
async
concurrency
semaphore
Intermediate
8 steps
javascript
import { useCallback, useRef, useState } from 'react'; export function ColorPicker({ initialColor = '#3b82f6', onCommit }) { const [committed, setCommitted] = useState(initialColor);
A validated color picker in React
uncontrolled-inputs
refs
validation
Intermediate
7 steps
go
package api import ( "errors"
Turning Gin validation errors into JSON
validation
error-handling
http-handlers
Intermediate
9 steps
php
<?php namespace App\Providers;
Defining authorization gates in Laravel
authorization
gates
service-provider
Intermediate
6 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.