basic logger middleware and formatting

This commit is contained in:
Michael Thomson 2025-02-09 00:43:50 -05:00
parent c10cc07324
commit 8f8e83a0d7
No known key found for this signature in database
GPG Key ID: 8EFECCD347C72F7D
4 changed files with 21 additions and 6 deletions

View File

@ -2,8 +2,11 @@ package main
import (
"database/sql"
"fmt"
"log"
"log/slog"
"net/http"
"os"
"gitea.michaelthomson.dev/mthomson/habits/internal/migrate"
todohandler "gitea.michaelthomson.dev/mthomson/habits/internal/todo/handler"
@ -12,7 +15,18 @@ import (
_ "github.com/mattn/go-sqlite3"
)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
slog.Info(fmt.Sprintf("[%s] %s", r.Method, r.URL))
next.ServeHTTP(w, r)
})
}
func main() {
// create logger
logger := slog.New(slog.NewTextHandler(os.Stdout, nil))
slog.SetDefault(logger)
// create db pool
db, err := sql.Open("sqlite3", "./habits.db")
if err != nil {
@ -34,14 +48,14 @@ func main() {
mux := http.NewServeMux()
// register handlers
mux.Handle("GET /todo/{id}", todohandler.HandleTodoGet(todoService))
mux.Handle("GET /todo/{id}", loggingMiddleware(todohandler.HandleTodoGet(todoService)))
mux.Handle("POST /todo", todohandler.HandleTodoCreate(todoService))
mux.Handle("DELETE /todo/{id}", todohandler.HandleTodoDelete(todoService))
mux.Handle("PUT /todo/{id}", todohandler.HandleTodoUpdate(todoService))
// create server
server := &http.Server{
Addr: ":8080",
Addr: ":8080",
Handler: mux,
}

View File

@ -5,6 +5,7 @@ import (
"embed"
"fmt"
"log"
"log/slog"
_ "github.com/mattn/go-sqlite3"
)
@ -18,6 +19,7 @@ type Migration struct {
}
func Migrate(db *sql.DB) {
slog.Info("Running migrations...")
migrationTableSql := `
CREATE TABLE IF NOT EXISTS migrations(
version INTEGER PRIMARY KEY,
@ -35,12 +37,11 @@ func Migrate(db *sql.DB) {
}
for _, file := range files {
fmt.Printf("Checking file: %s\n", file.Name())
var migration Migration
row := db.QueryRow("SELECT * FROM migrations WHERE name = ?;", file.Name())
err = row.Scan(&migration.Version, &migration.Name)
if err == sql.ErrNoRows {
fmt.Printf("Running migration: %s\n", file.Name())
slog.Info(fmt.Sprintf("Running migration: %s", file.Name()))
migrationSql, err := migrations.ReadFile(fmt.Sprintf("migrations/%s", file.Name()))
if err != nil {
log.Fatal(err)
@ -57,4 +58,5 @@ func Migrate(db *sql.DB) {
}
}
}
slog.Info("Migrations completed")
}

View File

@ -16,7 +16,6 @@ func NewInMemoryTodoRepository() InMemoryTodoRepository {
}
}
func (r *InMemoryTodoRepository) GetById(id int64) (repository.TodoRow, error) {
todo, found := r.Db[id]

View File

@ -9,7 +9,7 @@ var (
)
type TodoRow struct {
Id int64
Id int64
Name string
Done bool
}