commit a1278147f40954ebeea75cce3d58f345fb1d78c5 Author: Marc Cataford Date: Sun Oct 6 10:18:16 2024 -0400 feat: split out app boilerplate diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..b46778e --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module http-api-kit + +go 1.23.1 diff --git a/main.go b/main.go new file mode 100644 index 0000000..706d3bd --- /dev/null +++ b/main.go @@ -0,0 +1,75 @@ +package main + +import ( + "net/http" + "time" +) + +type Route struct { + Path string + Handler http.HandlerFunc + Static bool + StaticPath string +} + +type BackgroundTask struct { + Handler func() + Interval time.Duration +} + +type App struct { + Routes []Route + BackgroundTasks []BackgroundTask + StaticRoot string + Middleware []Middleware +} + +func (a *App) AddRoute(path string, handler http.HandlerFunc) { + a.Routes = append(a.Routes, Route{Path: path, Handler: handler}) +} + +func (a *App) AddStaticRoute(path string, filePath string) { + a.Routes = append(a.Routes, Route{Path: path, Static: true, StaticPath: filePath}) +} + +func (a *App) AddMiddleware(m Middleware) { + a.Middleware = append(a.Middleware, m) +} + +func (a *App) AddBackgroundTask(b BackgroundTask) { + a.BackgroundTasks = append(a.BackgroundTasks, b) +} + +func (a App) Start(addr string) { + for _, route := range a.Routes { + if route.Static { + http.Handle(route.Path, http.StripPrefix(route.Path, http.FileServer(http.Dir(route.StaticPath)))) + continue + } + + handler := route.Handler + + for _, mware := range a.Middleware { + handler = mware(handler) + } + + http.HandleFunc(route.Path, handler) + } + + for _, task := range a.BackgroundTasks { + go func() { + for { + task.Handler() + time.Sleep(task.Interval) + } + }() + } + + http.ListenAndServe(addr, nil) +} + +func NewApp() *App { + app := App{} + + return &app +} diff --git a/middleware.go b/middleware.go new file mode 100644 index 0000000..ee0aa3d --- /dev/null +++ b/middleware.go @@ -0,0 +1,18 @@ +package main + +import ( + "fmt" + "log/slog" + "net/http" + "time" +) + +type Middleware = func(http.HandlerFunc) http.HandlerFunc + +func LoggingMiddleware(f http.HandlerFunc) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + start := time.Now() + f(w, r) + slog.Info(fmt.Sprintf("%s - %s (%dms)", r.Method, r.URL, time.Now().Sub(start).Milliseconds())) + } +}