basic logger middleware and formatting

This commit is contained in:
2025-02-09 00:43:50 -05:00
parent c10cc07324
commit 8f8e83a0d7
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,
}