避免在Gin中的根路由上出现404错误。

huangapple go评论74阅读模式
英文:

Avoid 404 on root route using Gin

问题

我正在进行一个 CMS 项目,前端的 URL 是 https://cms.example.com

然而,后端的路由以 /v1 开头,我在 gin 中配置了一个路由组 engine.Group("/v1")。因此,后端的端点将是类似于 https://cms.example.com/v1/endpoint 的形式。

我还设置了一个 NoRoute 处理函数:

var errRouteNotFound = errors.New("route not found")
s.engine.NoRoute(func(c *gin.Context) {
 c.AbortWithError(http.StatusNotFound, errRouteNotFound)
})

我面临的问题是,每当有人访问前端时,我在后端日志中会收到关于 GET 请求 / 的 404 错误。在不更改路由模式的情况下,我该如何避免这些日志记录呢?因为它是一个更大项目的一部分。

编辑:我正在使用自定义日志记录器。

英文:

I am working on a CMS project where the URL for the frontend is https://cms.example.com

However, the backend routes start with /v1 which I have configured in gin as a Router Group engine.Group("/v1"). Hence a backend endpoint will be something like https://cms.example.com/v1/endpoint

I've also set a NoRoute handler function:

var errRouteNotFound = errors.New("route not found")
s.engine.NoRoute(func(c *gin.Context) {
 c.AbortWithError(http.StatusNotFound, errRouteNotFound)
})

The issue I am facing is that whenever someone visits the frontend, I get a 404 error for GET request on / in the backend logs. How can I avoid getting these logs without changing the route schema as it's part of a bigger project?

Edit: I am using a custom logger.

答案1

得分: 1

我找到了解决方案:

如果使用gin的日志记录器

请使用这个答案。感谢@EmilePels。

如果使用自定义日志记录器

在日志记录器函数中使用以下代码:

requestURL := c.Request.URL.String()
if requestURL == "/" {
  return
}
英文:

I found the solution:

In case gin's logger is used

Use this answer. Thanks to @EmilePels.

In case of a custom logger

Use something like this in the logger function:

requestURL := c.Request.URL.String()
if requestURL == "/" {
  return
}

huangapple
  • 本文由 发表于 2023年2月23日 15:58:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75541989.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定