在使用 Go 的 Gin Web 框架的時候,發現一個有趣的問題,curl 一個 router 是正常的,可是加上 -I 參數就 404 了,就像下面這樣git
package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
正常的github
curl http://127.0.0.1:8080/ping {"message":"pong"}
404的json
curl -I http://127.0.0.1:8080/ping HTTP/1.1 404 Not Found Content-Type: text/plain Date: Wed, 31 Oct 2018 04:35:22 GMT Content-Length: 18
而後經過抓包發現,curl -I 的 http method 是 HEAD,可是咱們只定義了GET,因此它就理所固然的 404 了架構
大部分時候這個樣子,對咱們也沒什麼影響,可是部分 slb 在對 http 服務作健康檢查的時候,用的 HEAD 的 method,並且只認爲 2xx 是正常的,因此,對於部分 router 咱們能夠用 Any 方法來註冊全部 method 的路由,保證健康檢查的正確性app
package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.Any("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 }
結果框架
curl -I http://127.0.0.1:8080/ping HTTP/1.1 200 OK Content-Type: application/json; charset=utf-8 Date: Wed, 31 Oct 2018 05:13:20 GMT Content-Length: 18
這個 Any 方法十分簡單實用curl
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() }
更多架構、PHP、GO相關踩坑實踐技巧請關注個人公衆號:PHP架構師 url