2024-10-06 14:34:17 +00:00
|
|
|
package httpapi
|
2024-10-06 14:18:16 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|