I am developing a RESTful API with Go but owing to app configuration, authentication etc I have quite a few global variables.
I am using Julien Schmidt's httprouter because of popular recommendation and am looking for a feasible way to avoid global variables.
Here is some of the code.
I am using a middleware for authenticating a user using gorrila/securecookie.
func AuthMiddleware(handler httprouter.Handle, isLoggedIn bool) httprouter.Handle {
return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {if isLoggedIn {
currUser, err := GetCurrentUser(r)
if currUser.Username != "" {
handler(w, r, ps)
return
}
responseWriter(w, false, "User not logged in", nil)
return
}
handler(w, r, ps)
}
}
After this, I want to be able to use the currUser object inside the handler that the request is forwarded to such as this one instead of calling GetCurrentUser once again
func foobar(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
var currQuestion CurrQuestions
err = Db.db.Raw("SELECT * FROM users WHERE U.user_id = ?", currUser.UserID).Find(&currQuestion).Error
if err != nil {
responseWriter(w, false, "Internal Server Error", "")
return
}
responseWriter(w, true, "", GameData{})
}