At the moment, I try to create a small Web-Project using Go for data handling on the server.
I try to pass my database-connection to my HandlerFunc(tions) but it does not work as expected. I am pretty new to golang, so maybe I did not understand some basic principles of this lang.
My main func looks like this:
func main() {
db, err := config.NewDB("username:password@/databasename?charset=utf8&parseTime=True")
if err != nil {
log.Panic(err)
}
env := &config.Env{DB: db}
router := NewRouter(env)
log.Fatal(http.ListenAndServe(":8080", router))
}
My Router:
func NewRouter(env *config.Env) *mux.Router {
router := mux.NewRouter().StrictSlash(true)
for _, route := range routes {
var handler http.Handler
handler = route.HandlerFunc
handler = Logger(handler, route.Name)
router.
Methods(route.Method).
Path(route.Pattern).
Name(route.Name).
Handler(handler)
}
return router
}
and my routes:
type Route struct {
Name string
Method string
Pattern string
HandlerFunc http.HandlerFunc
}
type Routes []Route
var routes = Routes{
Route{
"Index",
"GET",
"/",
controller.Index,
},
Route{
"Show",
"GET",
"/todos/{todoId}",
controller.TodoShow,
},
Route{
"Create",
"POST",
"/todos",
controller.TodoCreate,
},
}
So - how can I pass my "env" (or env.DB) to my FuncHandlers? I tried many things, but none of them worked.