Where should I store the database instance after initializing it in go? I want to access them from the request handlers.
// server.go
storage, err := config.GetFileStorage(viper.GetViper())
if err != nil {
log.Fatal(fmt.Sprintf("Failed to configure the file storage: %v
", err))
}
db, err := config.GetDatabase(viper.GetViper())
if err != nil {
log.Fatal(fmt.Sprintf("Failed to configure the database: %v
", err))
}
This are just local variables in the main function. How could I expose them now to the go package with the handlers?
You can wrap the DB connection in a struct, and have it return your http handlers. Something like 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 FROM world")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer rows.Close()
for rows.Next() {
// do 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 your object can handle concurrent access like *sql.DB https://golang.org/pkg/database/sql/#DB
If you want/need to share more across the handlers you can take a look at the environment pattern: http://www.jerf.org/iri/post/2929