1. 自定义 HTTP 配置
func main() {
r := gin.Default()
http.ListenAndServe(":8080", r)
}
或者
func main() {
r := gin.Default()
s := &http.Server{
Addr: ":8080",
Handler: r,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}
2. 使用 HTTP 方法
HTTP
协议支持的方法 GET
、HEAD
、POST
、PUT
、DELETE
、OPTIONS
、TRACE
、PATCH
、CONNECT
等都在 Gin
框架中都得到了支持。
func main() {
// Creates a gin router with default middleware:
// logger and recovery (crash-free) middleware
router := gin.Default()
router.GET("/someGet", getting)
router.POST("/somePost", posting)
router.PUT("/somePut", putting)
router.DELETE("/someDelete", deleting)
router.PATCH("/somePatch", patching)
router.HEAD("/someHead", head)
router.OPTIONS("/someOptions", options)
// By default it serves on :8080 unless a
// PORT environment variable was defined.
router.Run()
// router.Run(":3000") for a hard coded port
}
在 Gin
中特别定义了一个 Any()
方法,在 routergroup.go
文件中可看到具体定义 ,它能匹配以上 9 个 HTTP
方法,具体定义如下:
func (group *RouterGroup) Any(relativePath string, handlers ...HandlerFunc) IRoutes {group.handle("GET", relativePath, handlers)
group.handle("POST", relativePath, handlers)
group.handle("PUT", relativePath, handlers)
group.handle("PATCH", relativePath, handlers)
group.handle("HEAD", relativePath, handlers)
group.handle("OPTIONS", relativePath, handlers)
group.handle("DELETE", relativePath, handlers)
group.handle("CONNECT", relativePath, handlers)
group.handle("TRACE", relativePath, handlers)
return group.returnObj() }
3. 自定义请求 url 不存在时的返回值
// NoResponse 请求的 url 不存在,返回 404
func NoResponse(c *gin.Context) {
// 返回 404 状态码
c.String(http.StatusNotFound, "404, page not exists!")
}
func main() {
router := gin.Default()
// 设定请求 url 不存在的返回值
router.NoRoute(NoResponse)
router.Run(":8080")
}
输出结果:
$ curl http://127.0.0.1:8080/bar
404, page not exists!
4. 自定义重定向
生成 HTTP 重定向很方便,内部重定向和外部重定向都支持。
r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com/")
})
在浏览器中访问 [http://127.0.0.1:8080/test](http://127.0.0.1:8080/test)
会跳转到 www.baidu.com
页面。
要从 POST 方法重定向,可以参考: Redirect from POST ends in 404
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"})
})