Go Gin 框架 curl -I 返回 404 的問題

在使用 Go 的 Gin Web 框架的時候,發現一個有趣的問題,curl 一個 router 是正常的,但是加上 -I 參數就 404 了,就像下面這樣

package mainimport "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}

正常的

curl http://127.0.0.1:8080/ping{"message":"pong"}

404的

curl -I http://127.0.0.1:8080/ping



HTTP/1.1 404 Not FoundContent-Type: text/plainDate: Wed, 31 Oct 2018 04:35:22 GMTContent-Length: 18

然後通過抓包發現,curl -I 的 http method 是 HEAD,但是我們只定義了GET,所以它就理所當然的 404 了

大部分時候這個樣子,對我們也沒什麼影響,但是部分 slb 在對 http 服務做健康檢查的時候,用的 HEAD 的 method,而且只認爲 2xx 是正常的,所以,對於部分 router 我們可以用 Any 方法來註冊所有 method 的路由,保證健康檢查的正確性

package mainimport "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 OKContent-Type: application/json; charset=utf-8Date: Wed, 31 Oct 2018 05:13:20 GMTContent-Length: 18

這個 Any 方法十分簡單實用

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章