You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

57 lines
1.1 KiB
Go

package main
import (
1 year ago
"database/sql"
"flag"
"log"
"net/http"
"os"
1 year ago
"gitea.wagshome.duckdns.org/nathan/golearn/internal/models"
_ "github.com/go-sql-driver/mysql"
)
1 year ago
type application struct {
errorLog *log.Logger
infoLog *log.Logger
1 year ago
snippets *models.SnippetModel
1 year ago
}
func main() {
addr := flag.String("addr", ":4000", "HTTP network address")
1 year ago
dsn := flag.String("dsn", "web:pass@/snippetbox?parseTime=true", "MySQL data source name")
flag.Parse()
infoLog := log.New(os.Stdout, "INFO\t", log.Ldate|log.Ltime)
errorLog := log.New(os.Stderr, "ERROR\t", log.Ldate|log.Ltime|log.Lshortfile)
1 year ago
db, err := openDB(*dsn)
if err != nil {
errorLog.Fatal(err)
}
defer db.Close()
1 year ago
app := &application{
errorLog: errorLog,
infoLog: infoLog,
1 year ago
snippets: &models.SnippetModel{DB: db},
1 year ago
}
srv := &http.Server{
Addr: *addr,
ErrorLog: errorLog,
1 year ago
Handler: app.routes(),
}
infoLog.Printf("Starting server on %s", *addr)
1 year ago
err = srv.ListenAndServe()
errorLog.Fatal(err)
}
1 year ago
func openDB(dsn string) (*sql.DB, error) {
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil, err
}
if err = db.Ping(); err != nil {
return nil, err
}
return db, nil
}