I am currently building a web application in golang (with Gorilla) and have implemented several API endpoints. However, I noticed that every time I implement a function like
func CreateUserHandler(w http.ResponseWriter, r *http.Request) {}
I need to add the function below to the body of the handler functions to check if the request is allowed:
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 is happening to me right now is that I have to add a checkAuthorizedUser()handler function to each function, and so far I already have many handler functions. I wonder if there is a better way to check if a client is allowed access to a specific endpoint, besides explicitly authenticating each handler function.