英文:
gin gonic middleware, how to get failure/success status for next handler in chain
问题
我正在编写一个中间件,使用gin gonic golang框架。我想在我的中间件中知道如果调用下一个处理程序失败,并根据此采取行动。
func foo() gin.HandlerFunc {
//做一些事情..
c.Next()
//根据c.Next()的结果做一些事情
}
我该如何做到这一点?Next
的文档没有提供太多信息:https://godoc.org/github.com/gin-gonic/gin#Context.Next
你能给出一些建议吗?我基本上想检查不存在的API端点,例如,如果有人输入一个我们没有任何API端点的URL,我能在这里检测到吗?
英文:
I am writing a middleware, using gin gonic golang framework. I want to know within my middleware, if the call to next handler failed and take action based on that.
func foo() gin.HandlerFunc {
//do something..
c.Next()
//do something based on result of c.Next()
}
How can I do that? Documentation for next doesnt give much information https://godoc.org/github.com/gin-gonic/gin#Context.Next
Can you offer any suggestions. I basically want to check for non-existing api endpoints, for example, someone enters a URL, for which we don't have any api endpoint, then can I detect it here.
答案1
得分: 4
我将回答我的问题,因为我找到了一种处理路由未找到/方法未找到等问题的方法。思路是在NoRoute/NoMethod处理程序中使用context.Error()在gin上下文中设置一个错误。这将在c.Errors的错误切片中添加一个错误,然后可以在您的中间件函数中稍后使用。
func MyMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// 在这里做一些操作
c.Next()
// 根据c中的错误做一些操作
if c.Errors.Error() != nil {
// 错误情况,退出
return
}
// 否则继续正常处理
}
}
engine.NoRoute(func(c *gin.Context) {
c.JSON(404,
gin.H{"error": gin.H{
"key": "not allowed",
"description": "not allowed",
}})
c.Error(errors.New("Failed to find route")) // 在这里设置错误
})
希望对你有帮助。
英文:
I am going to answer my question since I found a way to handle this kind of issues with route not found / method not found etc. The idea is to set an error in the gin context using context.Error() from the NoRoute/NoMethod handlers. This adds an error to the slice of errors in the c.Errors, which can then later on be used inside your middleware function.
func MyMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
//do something here
c.Next()
//do something based on error in c.
if c.Errors.Error() != nil {
//error case, get out
return
}
//else continue regular processing.
}
}
engine.NoRoute(func(c *gin.Context) {
c.JSON(404,
gin.H{"error": gin.H{
"key": "not allowed",
"description": "not allowed",
}})
c.Error(errors.New("Failed to find route")) //Set the error here.
})
Hope it helps.
答案2
得分: 1
Engine
上有一个名为 NoRoute
的方法,你可以传递路由处理程序来处理 404 等情况。
英文:
There is a method on Engine
called NoRoute
that you can pass route handlers to handle 404's and such.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论