1. 程式人生 > >Go Gin 框架 curl -I 返回 404 的問題

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

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


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
}

正常的


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 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 的路由,保證健康檢查的正確性

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 方法十分簡單實用

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架構師