在使用 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架构师