I'm currently trying to create a small web project using Go to process data on a server.
I am trying to pass my database connection to my HandlerFunc (), but it is not working properly. I am new to the golang, so perhaps I did not understand some of the basic principles of this language.
My main function is as follows:
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 a lot, but none of them worked.