Gin 使用示例(二十九):重定向


Gin 框架支持内部和外部重定向:

func main()  {
    r := gin.Default()
    
    // HTTP 重定向
    r.GET("/test", func(c *gin.Context) {
        c.Redirect(http.StatusMovedPermanently, "https://www.xueyuanjun.com/")
    })
    
    // 路由重定向
    r.GET("/test1", func(c *gin.Context) {
        c.Request.URL.Path = "/test2"
        r.HandleContext(c)
    })
    r.GET("/test2", func(c *gin.Context) {
        c.JSON(200, gin.H{"hello": "world"})
    })
    
    r.Run()
}

运行上述代码启动服务器,在终端窗口通过 curl 进行测试:

-w653


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Gin 使用示例(二十八):查询字符串参数底层解析

>> 下一篇: Gin 使用示例(三十):运行多个服务器