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架构师

转载于:https://my.oschina.net/u/222608/blog/2395918

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值