所谓重定向,就是将原始的 URL 变为一个新的 URL,然后用新 URL 路由到的处理器中。<br />Gin中重定向很简单。内部、外部重定向均支持。最常用的,在 HandlerFunc 中调用 c.Redirect 方法即可。
r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
})
通过 POST 方法进行 HTTP 重定向
r.POST("/test", func(c *gin.Context) {
c.Redirect(http.StatusFound, "/foo")
})
或者用路由重定向,使用 c.HandleContext
r.GET("/test", 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"})
})