Configs2026年4月12日·1 分钟阅读

Gin — High-Performance HTTP Web Framework for Go

Gin is a high-performance HTTP web framework written in Go. Provides a Martini-like API but with significantly better performance — up to 40 times faster thanks to httprouter. The most popular Go web framework for REST APIs and microservices.

AI
AI Open Source · Community
快速使用

先拿来用,再决定要不要深挖

这里应该同时让用户和 Agent 知道第一步该复制什么、安装什么、落到哪里。

mkdir my-api && cd my-api
go mod init my-api
go get github.com/gin-gonic/gin
// main.go
package main

import (
    "net/http"
    "github.com/gin-gonic/gin"
)

type Asset struct {
    ID    int    `json:"id"`
    Repo  string `json:"repo"  binding:"required"`
    Stars int    `json:"stars" binding:"gte=0"`
}

var assets = []Asset{
    {1, "react", 230000},
    {2, "vue", 210000},
}

func main() {
    r := gin.Default()

    r.GET("/api/assets", func(c *gin.Context) {
        c.JSON(http.StatusOK, assets)
    })

    r.POST("/api/assets", func(c *gin.Context) {
        var a Asset
        if err := c.ShouldBindJSON(&a); err != nil {
            c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
            return
        }
        a.ID = len(assets) + 1
        assets = append(assets, a)
        c.JSON(http.StatusCreated, a)
    })

    r.Run(":8080")
}
go run main.go
curl http://localhost:8080/api/assets
介绍

Gin is the most popular HTTP web framework for Go. It uses httprouter for fast routing and provides a rich middleware system similar to Express (for Node) or Martini (for Go, its predecessor). Gin is designed for building REST APIs, web applications, and microservices at scale.

What Gin Does

  • Fast routing — radix tree via httprouter
  • Middleware — Logger, Recovery, CORS, BasicAuth, custom
  • JSON binding — ShouldBindJSON with validation tags
  • Validation — struct-level validation via go-playground/validator
  • Grouping — route groups with shared middleware
  • Error management — error collection in context
  • Rendering — JSON, XML, YAML, ProtoBuf, HTML templates
  • File uploads — single and multi-file
  • Graceful shutdownhttp.Server.Shutdown()
  • Testing — httptest integration

Architecture

Radix tree router for O(1) path matching. Context object carries request, response, params, and abort chain. Middleware are handler functions chained via c.Next(). Group routers share prefix and middleware. Engine implements http.Handler interface.

Self-Hosting

GIN_MODE=release go build -o server .
./server
# Deploy as single binary anywhere

Key Features

  • Fastest Go router
  • Express-like middleware
  • JSON validation via tags
  • Route groups
  • HTML template rendering
  • File upload handling
  • Graceful shutdown
  • Comprehensive logging
  • Easy testing with httptest

Comparison

Framework Router Middleware Performance
Gin httprouter (radix) Express-like Very fast
Echo Own (radix) Express-like Very fast
Fiber Fasthttp Express-like Fastest
Chi stdlib-compatible stdlib Fast
Gorilla Mux Regex-based stdlib Medium

常见问题 FAQ

Q: Gin vs Echo? A: 功能和性能几乎一样。Gin 社区更大、star 最多;Echo 文档更好、路由组织更优雅。看团队偏好。

Q: 能和标准库一起用吗? A: Gin 实现了 http.Handler 接口,可以嵌入 stdlib 的 http.Server。也可以混合使用 stdlib middleware。

Q: 生产环境用? A: 设置 GIN_MODE=release 关闭 debug 日志。Gin 在无数生产项目中使用(字节跳动、滴滴、七牛等大厂都有案例)。

来源与致谢 Sources

讨论

登录后参与讨论。
还没有评论,来写第一条吧。

相关资产