go - Where should I store global database instance? -
where should store database instance after initializing in go? want access them request handlers.
// server.go storage, err := config.getfilestorage(viper.getviper()) if err != nil { log.fatal(fmt.sprintf("failed configure file storage: %v\n", err)) } db, err := config.getdatabase(viper.getviper()) if err != nil { log.fatal(fmt.sprintf("failed configure database: %v\n", err)) }
this local variables in main function. how expose them go package handlers?
you can wrap db connection in struct, , have return http handlers. this:
package main import ( "database/sql" "log" "net/http" ) type dbmanager struct { db *sql.db } func (m *dbmanager) hellohandler() http.handler { return http.handlerfunc(func(w http.responsewriter, r *http.request) { rows, err := m.db.query("select hello world") if err != nil { http.error(w, err.error(), http.statusinternalservererror) return } defer rows.close() rows.next() { // stuff } }) } func main() { db, err := sql.open("", "") if err != nil { panic(err) } m := dbmanager{db: db} http.handle("/", m.hellohandler()) log.fatal(http.listenandserve(":8080", nil)) }
also make sure object can handle concurrent access *sql.db https://golang.org/pkg/database/sql/#db
if want/need share more across handlers can take @ environment pattern: http://www.jerf.org/iri/post/2929
Comments
Post a Comment