summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorMatthew Lemon <y@yulqen.org>2024-02-09 16:16:34 +0000
committerMatthew Lemon <y@yulqen.org>2024-02-09 16:16:34 +0000
commitb8ed10b800d24a94bb6a9339d5764c6dbe7d9f6e (patch)
tree603865502278e453b1d67adcd2e04655c2894cc6
parented2cb5414da47a225fe2080a7cf4e3c685a129ec (diff)
Adds the database driver and opens database pool
Adds the new -dsn flag so that the user can pass any database into the program. Adds a new function that wraps sql.Open() to create the connection pool, and pings it to ensure it is alive.
-rw-r--r--cmd/web/main.go40
1 files changed, 36 insertions, 4 deletions
diff --git a/cmd/web/main.go b/cmd/web/main.go
index a4082fd..b767275 100644
--- a/cmd/web/main.go
+++ b/cmd/web/main.go
@@ -1,11 +1,13 @@
package main
import (
+ "database/sql"
"flag"
- "log"
"log/slog"
"net/http"
"os"
+
+ _ "github.com/go-sql-driver/mysql"
)
type application struct {
@@ -14,17 +16,47 @@ type application struct {
func main() {
addr := flag.String("addr", ":4000", "HTTP network port")
- // dsn := flag.String("dsn", "web:dedpassword:/ded?parseTime=true", "MySQL data source name")
+ dsn := flag.String("dsn", "web:dedpassword@/ded?parseTime=true", "MySQL data source name")
flag.Parse()
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
+
+ // Database connection
+ db, err := openDB(*dsn)
+ if err != nil {
+ logger.Error(err.Error())
+ os.Exit(1)
+ }
+
+ defer db.Close()
+
app := &application{
logger: logger,
}
+
// mux := http.NewServeMux()
// mux.HandleFunc("/", home)
// log.Print("starting server on :4000")
logger.Info("starting server", "addr", *addr)
- err := http.ListenAndServe(*addr, app.routes())
- log.Fatal(err)
+ err = http.ListenAndServe(*addr, app.routes())
+ logger.Error(err.Error())
+ os.Exit(1)
+}
+
+// openDB wraps sql.Open() and returns a sql.DB connection pool
+// for a given DSN.
+func openDB(dsn string) (*sql.DB, error) {
+ db, err := sql.Open("mysql", dsn)
+ if err != nil {
+ return nil, err
+ }
+
+ err = db.Ping()
+ if err != nil {
+ db.Close()
+ return nil, err
+ }
+
+ return db, nil
+
}