I'm having trouble handling connections in a golang web app that uses MySQL.
In the tutorials I have seen the database interaction is all handled once, in the main function.
However, in the real world each http request will interact with the database - where should I keep sql.Open() and defer sql.Close()? Here is my code.
package main
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"html/template"
"net/http"
)
var db *sql.DB
var pageTemplate = template.Must(template.ParseFiles("index.html"))
type Items []string
func main() {
db, err := sql.Open("mysql",
"username:passwordl@tcp(127.0.0.1:3306)/databasename")
checkErr(err)
defer db.Close()
_, err = db.Exec(
`
CREATE TABLE IF NOT EXISTS items (
item_id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
item TEXT
);
`)
checkErr(err)
http.HandleFunc("/", mainHandler)
http.ListenAndServe(":3000", nil)
}
func mainHandler(w http.ResponseWriter, r *http.Request) {
var item string
var items Items
stmt, err := db.Prepare("select item from items")
checkErr(err)
defer stmt.Close()
rows, err := stmt.Query()
checkErr(err)
defer rows.Close()
for rows.Next() {
err := rows.Scan(&item)
checkErr(err)
items = append(items, item)
}
if err = rows.Err(); err != nil {
checkErr(err)
}
pageTemplate.Execute(w, items)
}
func checkErr(err error) {
if err != nil {
fmt.Println(err)
}
}
I get a runtime error on the line:
stmt, err := db.Prepare("select item from items")
Persumably because the db isn't recognised outside of the main function. Should I instead have sql.Open() on each url Handler?
Apologies if the question is ambiguous.