3
votes

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.

2
have you resolve this?I have same questionR wang

2 Answers

1
votes

There is a method on Engine called NoRoute that you can pass route handlers to handle 404's and such.

1
votes

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.