安装与使用
安装
go get -u github.com/gin-gonic/gin
示例
package main
import (
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
// 创建一个默认的路由引擎
r := gin.Default()
// 添加中间件(可选)
r.Use(gin.Logger()) // 增加日志
r.Use(gin.Recovery()) // 全局异常处理
// 定义一个 GET 请求的路由,路径为 "/ping"
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "pong",
})
})
// 定义一个带参数的路由
r.GET("/hello/:name", func(c *gin.Context) {
name := c.Param("name")
c.JSON(http.StatusOK, gin.H{
"message": "Hello " + name,
})
})
// 启动 HTTP 服务器,默认监听在 0.0.0.0:8080
r.Run() // 等价于 r.Run(":8080")
}
过程中的问题
# 1. 进入项目根目录,初始化Go模块
go mod init go_gin_study
# 2. 安装依赖
go mod tidy