Go Gin 快速学习 【重定向和路由】
重定向
路由重定向
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/redirect", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "https://www.baidu.com")
})
router.Run(":8080")
}
HTTP 重定向
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
router := gin.Default()
router.GET("/redirect-router", func(c *gin.Context) {
c.Request.URL.Path = "/redirect"
// 路由重定向:手动处理上下文,触发路由处理
router.HandleContext(c)
})
router.GET("/redirect", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "redirect success",
})
})
router.Run(":8080")
}
Gin 路由
普通路由
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
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,
})
})
// 接受一切路由方式,包括 GET、POST、PUT、DELETE 等
r.Any("/test", func(c *gin.Context) {
name := c.Param("name")
c.JSON(http.StatusOK, gin.H{
"message": "Hello " + name,
})
})
//NoRoute 404 路由. 找不到路由的情况下, 会调用这个路由
r.NoRoute(func(c *gin.Context) {
c.JSON(http.StatusNotFound, gin.H{
"message": "404 Not Found",
})
})
// 启动 HTTP 服务器,默认监听在 0.0.0.0:8080
r.Run() // 等价于 r.Run(":8080")
}
路由组
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
//URL前缀的路由划分为一个路由组。习惯性一对{}包裹
// 创建一个默认的路由引擎
r := gin.Default()
routerGroup1 := r.Group("/api")
routerGroup1.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "api",
})
})
routerGroup2 := r.Group("/api2")
routerGroup2.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"message": "api2",
})
})
r.Run()
}
路由原理
Gin框架中的路由使用的是httprouter这个库。

浙公网安备 33010602011771号