feat: split out app boilerplate
This commit is contained in:
commit
a1278147f4
3 changed files with 96 additions and 0 deletions
3
go.mod
Normal file
3
go.mod
Normal file
|
@ -0,0 +1,3 @@
|
|||
module http-api-kit
|
||||
|
||||
go 1.23.1
|
75
main.go
Normal file
75
main.go
Normal file
|
@ -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
|
||||
}
|
18
middleware.go
Normal file
18
middleware.go
Normal file
|
@ -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()))
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue