![[../../../assets/images/pub/rzyd.webp]]
目录
体验内置库
可以先体验下go内置的http web库,net/http
main.go
package main
import (
"fmt"
"net/http"
)
func SayHello(w http.ResponseWriter, r *http.Request) {
// 写入响应
fmt.Fprintf(w, "hello world")
}
func main() {
// 路由,匹配后执行
http.HandleFunc("/hello", SayHello)
// 启动服务
err := http.ListenAndServe(":9000", nil)
if err != nil {
fmt.Printf("http server start failed, err: %v", err)
return
}
}
直接执行go run main.go
执行成功后,在浏览器地址栏中访问http://localhost:9000/hello即可
![[../../../assets/images/2026/Pasted image 20260130162329.png]]
什么是Gin?
Gin 是一个基于 Go 语言(Golang)的 服务端高性能 HTTP Web 框架,广泛用于构建 API 服务、Web 应用、微服务等场景。
Gin 的核心特性:
- 零分配路由器 —— 内存高效,无堆分配
- 高性能 —— 基准测试显示速度显著优于其他 Go web 框架
- 中间件支持 —— 可扩展中间件系统,支持认证、日志、CORS 等
- 防崩溃 —— 内置恢复中间件可防止 panic 引起的服务崩溃
- JSON 校验 —— 自动绑定和验证 JSON 请求/响应
- 路由分组 —— 组织相关路由并应用公共中间件
- 错误管理 —— 集中处理与日志记录所有错误
- 内置渲染 —— 支持 JSON, XML, HTML 模板等
- 可扩展 —— 社区中拥有大规模中间件和插件生态
快速体验Gin
安装
go get -u github.com/gin-gonic/gin
引入使用
main.go
package main
import "github.com/gin-gonic/gin"
func sayHello(c *gin.Context) {
// gin.H 是 map[string]interface{} 的一种快捷方式
c.JSON(200, gin.H{
"message": "hello world",
})
}
func main() {
gin.SetMode("release") // 设置gin的运行模式为release,默认为debug模式
router := gin.Default() // 创建默认路由引擎
// 指定用户使用GET请求访问/hello时,执行sayHello这个函数
router.GET("/hello", sayHello)
// 启动服务
err := router.Run(":9000")
if err != nil {
return
}
}
直接执行go run main.go
执行成功后,在浏览器地址栏中访问http://localhost:9000/hello即可
![[../../../assets/images/2026/Pasted image 20260130165836.png]]
响应封装
新建 res.go文件
package gin
import (
"github.com/gin-gonic/gin"
)
type Response struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data any `json:"data"`
}
func response(c *gin.Context, code int, msg string, data any) {
c.JSON(200, Response{
Code: code,
Msg: msg,
Data: data,
})
}
func Ok(c *gin.Context, data any, msg string) {
response(c, 0, msg, data)
}
func OkWithData(c *gin.Context, data any) {
Ok(c, data, "success")
}
func OkWithMsg(c *gin.Context, msg string) {
// nil前端调用返回值是 null, 使用gin.H{}, 前端调用返回值是 {}
Ok(c, gin.H{}, msg)
}
var codeMap = map[int]string{
1001: "权限错误",
1002: "参数错误",
}
func Fail(c *gin.Context, code int, data any, msg string) {
response(c, code, msg, data)
}
func FailWithMsg(c *gin.Context, msg string) {
response(c, 1001, msg, nil)
}
func FailWithCode(c *gin.Context, code int) {
msg, ok := codeMap[code]
if !ok {
msg = "未知错误"
}
response(c, code, msg, nil)
}
同包下可以直接在main.go中使用 main.go
package main
import "github.com/gin-gonic/gin"
func sayHello(c *gin.Context) {
// gin.H 是 map[string]interface{} 的一种快捷方式
c.JSON(200, gin.H{
"message": "hello world",
})
}
func main() {
router := gin.Default()
router.GET("/hello", sayHello)
router.GET("/login", func(c *gin.Context) {
OkWithMsg(c, "登录成功")
})
router.GET("/user", func(c *gin.Context) {
OkWithData(c, map[string]any{
"name": "张三",
"age": 23,
})
})
router.POST("/user", func(c *gin.Context) {
FailWithMsg(c, "参数错误")
})
// 启动服务
err := router.Run(":9000")
if err != nil {
return
}
}
可以使用热门的API管理工具:Postman、Apifox、Apipost 调试
生态与扩展
Gin 本身是「核心框架」,但生态丰富,可搭配以下工具满足复杂需求:
数据库:GORM(Go 语言 ORM 框架)、xorm; 认证授权:gin-jwt(JWT 认证)、gin-authz(基于 Casbin 的权限控制); 限流熔断:gin-rate-limit(限流)、hystrix-go(熔断); 日志监控:zap(高性能日志)、prometheus + grafana(监控); 模板渲染:Gin 内置 HTML 模板引擎(c.HTML()),支持模板继承、变量渲染; API 文档:swaggo/gin-swagger(自动生成 Swagger 文档)。
![[../../../assets/images/pub/clw.webp#pic_center)]]