Redirects(重定向)

发出HTTP重定向很容易。支持内部和外部位置。

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")
})

发出路由器重定向,使用如下所示的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"})
})

Custom HTTP configuration(自定义HTTP配置)

直接使用http.ListenAndServe(),如下所示:

func main() {
    router := gin.Default()
    http.ListenAndServe(":8080", router)
}

或者

func main() {
    router := gin.Default()

    s := &http.Server{
        Addr:           ":8080",
        Handler:        router,
        ReadTimeout:    10 * time.Second,
        WriteTimeout:   10 * time.Second,
        MaxHeaderBytes: 1 << 20,
    }
    s.ListenAndServe()
}