How to check authentication for hundreds and thousands of API endpoints?

Viewed 348

I am currently building a web application in golang (with Gorilla) and have implemented a handful of API endpoints. However, I noticed that every time I implement a function like

func CreateUserHandler(w http.ResponseWriter, r *http.Request) {}

I have to add the function below to the body of handler functions to check if request is authorized:

func checkAuthorizedUser (r * http.Request) error {
    uid, err := CheckRequestUser (r.Cookie("uid"))
    if err != nil {
        return errors.New("Can't find cookie value for uid")
    }
    if !IsValidUser (uid.Value) { 
        return errors.New("Not a valid user")
    }
    return nil
}

What happens to me right now is that I have to add checkAuthorizedUser() to every handler function, and I have already have a lot of handler functions so far. I wonder if there is a better way to check whether a client is authorized to access certain endpoint other than explicitly checking authentication in every handler function.

1 Answers
Related