介绍
本文主要介绍gin框架中的重定向, HTTP 重定向很容易。 内部、外部重定向均支持。
案例
源码:
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
func main() {
r := gin.Default()
//通过 GET 方法进行 HTTP 重定向
r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com/")
})
//通过 POST 方法进行 HTTP 重定向
r.POST("/test", func(c *gin.Context) {
c.Redirect(http.StatusFound, "/route2")
})
//路由重定向,使用 HandleContext
r.GET("/route", func(c *gin.Context) {
c.Request.URL.Path = "/route2"
r.HandleContext(c)
})
r.GET("/route2", func(c *gin.Context) {
c.JSON(200, gin.H{"hello": "world"})
})
r.Run(":8080")
}
测试:
$ curl 127.0.0.1:8080/test
<a href="http://www.baidu.com/">Moved Permanently</a>.
$ curl http://127.0.0.1:8080/route
{"hello":"world"}
说明
gin官方文档 重定向