Gin — framework web Go performant

VérifiéSûr

Construire des API HTTP en Go avec Gin : routage, groupes de routes, middleware, validation des requêtes et arrêt gracieux du serveur.

Spar Skills Guide Bot
DeveloppementIntermédiaire
17/11/2026
Claude CodeCursorWindsurfCopilotCodex
#go#http-api#middleware#routing#web-framework

Recommandé pour

Synthèse automatique

Cette skill décrit l'usage du framework web Go Gin : routage sur radix-tree, groupes de routes, chaînes de middleware, liaison et validation des corps de requête, et arrêt propre du serveur.

Points forts

  • Exemples de code directement exploitables pour les groupes versionnés, le middleware d'authentification et la validation via les tags `binding`
  • Explicite les pièges d'API réels : `gin.Default()` vs `gin.New()`, `ShouldBindJSON` qui renvoie une erreur au lieu d'interrompre, `c.Next()` / `c.Abort()`
  • Signale les bonnes pratiques de production : `GIN_MODE=release` et remplacement de `r.Run` par `http.Server` avec `Shutdown(ctx)`
  • Périmètre clairement assumé : framework non opinionné, la persistance et l'authentification restent à la charge du projet

Limites

  • Le fichier est tronqué au milieu de l'exemple 1 : la fonction `authMiddleware` s'arrête net, l'exemple n'est pas copiable tel quel
  • Incohérence de version : la section compatibilité annonce Go 1.21+ alors que le texte indique que le go.mod de Gin exige Go 1.26
  • Aucune indication sur les tests, le déploiement ou la structure de projet au-delà des routes
Quand l'utiliser

À utiliser pour créer ou faire évoluer une API HTTP en Go avec Gin, notamment pour les groupes de routes, le middleware, la validation ou l'arrêt gracieux.

Quand l'éviter

À éviter si le projet n'utilise pas Gin, ou s'il s'agit de choisir un framework, de concevoir la couche base de données ou de mettre en place une authentification complète.

Analyse de sécurité

Sûr
Score qualité75/100

The content is pure documentation: it teaches the Gin Go framework with illustrative code snippets, the only executable command being `go get github.com/gin-gonic/gin`, a standard public module install. There are no destructive operations, no exfiltration of secrets/tokens, no obfuscated or base64 payloads, no attempts to disable safety controls, and no embedded instructions aimed at the auditor. Tool usage (Go toolchain, network fetch of a public dependency) is ordinary for the stated purpose.

Aucun point d'attention détecté

Comment cette analyse est faite

Exemples

Scaffold a versioned API
Scaffold a Gin API in Go with a /api/v1 route group protected by a JWT middleware and a POST /orders handler that validates the JSON body with binding tags.
Graceful shutdown
Rewrite my Gin server so it uses http.Server with signal-based Shutdown instead of r.Run, without dropping in-flight requests.
Debug binding errors
My Gin handler always returns 400 on POST. Show me how to use ShouldBindJSON and return field-level validation errors instead of a raw error string.

name: gin description: >- Gin is a Go web framework with a Martini-like API and a zero-allocation router. Use it to build HTTP APIs that need routing, middleware, request binding/validation, JSON responses, and graceful shutdown with low per-request overhead. Use when a user asks to scaffold a Go HTTP API, add route groups or middleware, validate request bodies, or shut a Go server down cleanly. license: Apache-2.0 compatibility: "Go 1.21+ (the current gin release's go.mod requires Go 1.26)" metadata: author: terminal-skills version: "1.1.0" category: development tags: "go, web-framework, http, rest, middleware" repository: https://github.com/gin-gonic/gin

Gin — High-Performance Go Web Framework

Overview

Gin is a minimal, fast HTTP web framework for Go built on net/http with a radix-tree router (originally based on httprouter). It provides routing, route groups, middleware chaining, request binding/validation via go-playground/validator, and JSON/XML/YAML rendering helpers. It is unopinionated about project layout and data access — you wire in your own database and auth logic.

Instructions

Install

go get github.com/gin-gonic/gin

This adds github.com/gin-gonic/gin to go.mod. Gin's own go.mod currently requires Go 1.26 to build from source; a project that only imports Gin as a dependency needs a Go toolchain at least that new to resolve the module.

Build routes and middleware

  • gin.Default() returns an engine with the Logger and Recovery middleware attached; gin.New() returns a bare engine.
  • r.Group("/api") creates a route group; call .Use(middleware) on the group to scope middleware to it.
  • Middleware is a func(*gin.Context); call c.Next() to continue the chain or c.Abort()/c.AbortWithStatusJSON(...) to stop it.
  • c.ShouldBindJSON(&v) parses and validates the request body against struct binding tags, returning an error instead of aborting — check it yourself.
  • Set GIN_MODE=release (or gin.SetMode(gin.ReleaseMode)) in production; debug mode logs every route registration and is slower.

Shut down without dropping in-flight requests

Gin's own r.Run(":8080") blocks forever and has no shutdown hook, so production services run http.Server{Handler: r} directly and call Shutdown(ctx) on a signal, as in Example 2 below.

Examples

Example 1: "Add a versioned /api/v1 group with JWT auth and request validation"

package main

import (
	"net/http"
	"strconv"

	"github.com/gin-gonic/gin"
)

type CreateOrderRequest struct {
	ProductSKU string `json:"productSku" binding:"required"`
	Quantity   int    `json:"quantity" binding:"required,min=1"`
}

func main() {
	r := gin.Default() // Logger + Recovery middleware

	v1 := r.Group("/api/v1")
	v1.Use(authMiddleware())
	{
		v1.GET("/orders", listOrders)
		v1.POST("/orders", createOrder)
		v1.GET("/orders/:id", getOrder)
	}

	r.Run(":8080") // fine for local dev; see Example 2 for production
}

func listOrders(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))

	orders, total := store.FindOrders(page, limit)
	c.JSON(http.StatusOK, gin.H{"data": orders, "total": total, "page": page})
}

func createOrder(c *gin.Context) {
	var req CreateOrderRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	order, err := store.CreateOrder(req.ProductSKU, req.Quantity)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "could not create order"})
		return
	}
	c.JSON(http.StatusCreated, order)
}

func getOrder(c *gin.Context) {
	order, err := store.FindOrder(c.Param("id"))
	if err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "order not found"})
		return
	}
	c.JSON(http.StatusOK, order)
}

func authMiddleware() gin.HandlerFunc {
	return func(c *gin.Context) {
		token := c.GetHeader("Authorization")
		if token == "" {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing token"})
			return
		}
		user, err := validateJWT(token)
		if err != nil {
			c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid token"})
			return
		}
		c.Set("user", user)
		c.Next()
	}
}

Result: POST /api/v1/orders without a token returns 401 {"error":"missing token"}; with a valid token and a body missing quantity it returns 400 naming the failed validation; a valid request returns 201 with the created order.

Example 2: "Make the server shut down gracefully on SIGTERM so Kubernetes rollouts don't drop requests"

package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.GET("/healthz", func(c *gin.Context) { c.Status(http.StatusOK) })

	srv := &http.Server{Addr: ":8080", Handler: r}
	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %v", err)
		}
	}()

	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
	<-quit

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Printf("forced shutdown: %v", err)
	}
}

Result: on SIGTERM, the process stops accepting new connections and waits up to 5 seconds for in-flight requests to finish before exiting, instead of killing them mid-response.

Guidelines

  • Prefer ShouldBindJSON/ShouldBindQuery over the panicking BindJSON/BindQuery variants — the Should* forms return an error you handle, while the non-Should forms abort the request with a 400 for you, which is easy to forget and double-handle.
  • gin.H{} is a map[string]any alias — fine for ad-hoc responses, but use typed structs for anything with a documented response shape (OpenAPI, client codegen).
  • Middleware runs in registration order on the way in and reverse order after c.Next() returns, so put logging/recovery first and auth after CORS.
  • Gin does not include a built-in rate limiter, CORS handler, or JWT parser; pull in a dedicated middleware package (or write one) rather than reimplementing token parsing inline.
  • Debug mode (the default) logs every registered route and warns on stdout; always set GIN_MODE=release for production builds.
  • r.Run() has no graceful shutdown; use it only for local development, and switch to an explicit http.Server plus Shutdown(ctx) for anything deployed.

Du fichier au premier essai

Le téléchargement contient exactement le contenu affiché sur cette fiche. Cette copie peut différer de la dernière version du dépôt source.

Consulter la source et ses fichiers annexes

Ce téléchargement contient uniquement SKILL.md. Les scripts, références, modèles et dépendances éventuels ne sont pas inclus. Récupérez les fichiers nécessaires depuis la source en conservant leur arborescence avant de poursuivre.

1. Télécharger le fichier

Télécharger SKILL.md

Depuis la racine d’un projet de test, enregistrez le fichier sous .skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md, ou utilisez la commande suivante. Ce dossier sert à examiner la skill avant son installation.

Commande pour macOS/Linux ou WSL : un shell POSIX et curl sont nécessaires. Sous Windows sans WSL, utilisez le bouton de téléchargement et créez le dossier manuellement.

mkdir -p '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/gin-high-performance-go-web-framework-mwirmdwg/download' --output '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md.part' && mv '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md.part' '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md'

2. Vérifier les prérequis

Lisez SKILL.md avant de l’utiliser. Si le fichier cite des scripts ou services externes, examinez-les et préparez les accès nécessaires dans votre environnement de test.

Environnement déclaré par l’auteur : Go 1.21+ (the current gin release's go.mod requires Go 1.26)

Aucune section de prérequis reconnue dans ce fichier. Cela ne signifie pas qu’il est autonome : les bibliothèques, outils et accès peuvent être cités ailleurs dans le contenu ou dans le dépôt source.

Les plateformes de la fiche sont des indications du catalogue. Les chemins ci-dessous suivent la documentation des outils ; ils ne prouvent pas que cette skill y a été exécutée. Aucune version minimale de ces outils n’est attestée pour cette fiche.

3. Charger la skill

Après vérification, copiez le dossier complet dans le projet avec l’une des commandes ci-dessous, puis ouvrez une nouvelle session de l’outil. La commande s’arrête si un dossier du même nom existe déjà : comparez les fichiers avant de le remplacer.

Claude Code
test -f '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md' && test -s '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/gin' && cp -R '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg' '.claude/skills/gin'

Cursor
test -f '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md' && test -s '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md' && mkdir -p '.cursor/skills' && test ! -e '.cursor/skills/gin' && cp -R '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg' '.cursor/skills/gin'

Codex
test -f '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md' && test -s '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md' && mkdir -p '.agents/skills' && test ! -e '.agents/skills/gin' && cp -R '.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg' '.agents/skills/gin'

OpenSkills

OpenSkills doit déjà être installé. La procédure locale install/read est contrôlée avec OpenSkills 1.5.0, qui exige Node.js ≥ 20.6.0. Aucun slug du catalogue n’est résolu automatiquement.

Installation officielle d’OpenSkills
openskills install './.skill-downloads/gin-high-performance-go-web-framework-mwirmdwg'

openskills read 'gin-high-performance-go-web-framework-mwirmdwg'

La lecture doit afficher le contenu du fichier installé et son dossier de base. Elle ne lance ni la skill ni ses dépendances.

Pour un agent qui lit AGENTS.md, synchronisez ensuite l’index. Cette commande modifie AGENTS.md : relisez le diff avant de l’utiliser.

openskills sync

Mode manuel ou autre outil : joignez SKILL.md à une conversation, ou ouvrez-le dans un agent capable de lire les fichiers. Ajoutez les ressources annexes nécessaires. Il n’existe pas de dossier universel reconnu par tous les outils.

4. Faire un premier essai

Utilisez une entrée courte et fictive : un endpoint d’API, un petit document ou un brief d’interface. Dans une nouvelle conversation, joignez le fichier ou donnez son chemin à l’agent, puis adaptez cette demande :

Lis .skill-downloads/gin-high-performance-go-web-framework-mwirmdwg/SKILL.md et applique ses instructions à cet exemple : [décrire une entrée de test]. Indique les fichiers, dépendances ou accès qui manquent. Produis le résultat demandé par la skill sans inventer de données ni exécuter de script non examiné.

Résultat attendu : une sortie correspondant aux instructions de la skill, ou une liste précise des prérequis manquants. Une simple confirmation de lecture ne valide pas le premier usage. Si une ressource externe est indisponible, ce parcours reste à tester.

Skills similaires