feat: logger, middleware

This commit is contained in:
2026-03-24 22:50:13 +01:00
parent 8e9dc0b581
commit 7d81d1505a
4 changed files with 54 additions and 11 deletions
+15 -7
View File
@@ -13,6 +13,7 @@ import (
"github.com/joho/godotenv"
_ "github.com/lib/pq"
"greenlight.debuggingjon.dev/internal/data"
"greenlight.debuggingjon.dev/internal/jsonlog"
)
// Declare a string containing the application version number. Later in the book we'll
@@ -41,17 +42,20 @@ type config struct {
// logger, but it will grow to include a lot more as our build progresses.
type application struct {
config config
logger *log.Logger
logger *jsonlog.Logger
models data.Models
}
func main() {
logger := log.New(os.Stdout, "", log.Ldate|log.Ltime)
var cfg config
// Initialize a new jsonlog.Logger which writes any messages *at or above* the INFO
// severity level to the standard out stream.
logger := jsonlog.New(os.Stdout, jsonlog.LevelInfo)
err := godotenv.Load()
if err != nil {
logger.Fatal(err)
logger.PrintFatal(err, nil)
}
dsn := os.Getenv("DATABASE_DSN")
@@ -73,7 +77,7 @@ func main() {
// application immediately.
db, err := openDB(cfg)
if err != nil {
logger.Fatal(err)
logger.PrintFatal(err, nil)
}
// Defer a call to db.Close() so that the connection pool is closed before the
@@ -85,7 +89,7 @@ func main() {
}()
// Also log a message to say that the connection pool has been successfully
// established.
logger.Printf("database connection pool established")
logger.PrintInfo("database connection pool established", nil)
app := &application{
config: cfg,
@@ -98,13 +102,17 @@ func main() {
Addr: fmt.Sprintf(":%d", cfg.port),
Handler: app.routes(),
IdleTimeout: time.Minute,
ErrorLog: log.New(logger, "", 0),
ReadTimeout: 10 * time.Second,
WriteTimeout: 30 * time.Second,
}
logger.Printf("starting %s server on %s", cfg.env, srv.Addr)
logger.PrintInfo("starting server", map[string]string{
"addr": srv.Addr,
"env": cfg.env,
})
err = srv.ListenAndServe()
logger.Fatal(err)
logger.PrintFatal(err, nil)
}
func openDB(cfg config) (*sql.DB, error) {