I'm new to golang and I'm trying to build a micro service that connects to a database and serves json based on the endpoint that are hit.
func main() {
mux := httprouter.New()
mux.GET("/", index)
mux.GET("/adminUser", adminUserReturn)
http.ListenAndServe(":8080", mux)
}
func adminUserReturn(w http.ResponseWriter, req *http.Request, ps httprouter.Params) {
user := "homestead"
pass := "secret"
dbname := "test-db"
dbHost := "127.0.0.1"
dbPort := "33060"
db, err := sql.Open("mysql", user+":"+pass+"@tcp("+dbHost+":"+dbPort+")/"+dbname)
.
.
.
.
defer db.Close()
}
My question is should I "open" a connection in each endpoint then "close" the connection when the method is done executing? Or should I just initiate the sql.DB "instance" in the main function and defer db.Close() in main as well? That way the db connection will never close (assuming the program keeps running). Could this lead to the DB being overloaded with connections?
Aucun commentaire:
Enregistrer un commentaire