2

I have a user.save route (below) in my Golang API that can be used to create and update a user depending on whether an id was provided in the request object. The route uses the auth middleware which other routes do too.

api.POST("/user.save", auth(), user.Save())
api.POST("/user.somethingElse", auth(), user.SomethingElse())

Here is my middleware:

func auth() gin.HandlerFunc {
    return func(c *gin.Context) {
        //I would like to know here if user.save was the route called
        //do authy stuff
    }
}

I'm thinking that if I can detect in the auth middleware whether the user.save route was called I can then check to see if an id was included and decide whether to continue or return.

1
  • 1
    I would change my routes to be a little more REST like. something like: POST /users would create a user and PUT /users/{userID} would update the user. Then you could apply the appropriate middleware to each route. Commented Dec 23, 2015 at 17:08

1 Answer 1

9

You could check the url from the auth handler. The actual request is on the context, so it's as easy as:

if c.Request.URL.Path == "/user.save" {
    // Do your thing
}

Another solution is to parameterize your auth middleware, something like this:

api.POST("/user.save", auth(true), user.Save())
api.POST("/user.somethingElse", auth(false), user.SomethingElse())

func auth(isUserSave bool) gin.HandlerFunc {
    return func(c *gin.Context) {
        if isUserSave {
            // Do your thing
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.