first commit

This commit is contained in:
Robin Olsen
2026-01-31 16:00:23 +01:00
commit a3a1d71325
23 changed files with 614 additions and 0 deletions

45
cmd/web/server/routes.go Normal file
View File

@@ -0,0 +1,45 @@
package server
import (
"embed"
"net/http"
"strings"
"time"
"github.com/NYTimes/gziphandler"
"github.com/a-h/templ"
"github.com/rs/cors"
)
type Route struct {
Pattern string
Component templ.Component
}
func (s *Server) RegisterRoutes(assets embed.FS, routes []Route) http.Handler {
mux := http.NewServeMux()
s.handleAssets(mux, assets)
for _, route := range routes {
mux.Handle(route.Pattern, templ.Handler(route.Component))
}
handler := cors.Default().Handler(mux)
return gziphandler.GzipHandler(handler)
}
func (s *Server) handleAssets(mux *http.ServeMux, assets embed.FS) {
fileServer := http.FileServer(http.FS(assets))
mux.Handle("/assets/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Optionally set long-term caching headers for static assets
//w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
fileServer.ServeHTTP(w, r)
}))
mux.HandleFunc("/robots.txt", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "no-cache")
http.ServeContent(w, r, "robots.txt", time.Now(), strings.NewReader("User-agent: *\nAllow: /"))
})
}

32
cmd/web/server/server.go Normal file
View File

@@ -0,0 +1,32 @@
package server
import (
"embed"
"fmt"
"net/http"
"time"
"github.com/steveyegge/beads"
)
type Server struct {
Port int
Assets embed.FS
Routes []Route
Service beads.Storage
}
// NewServer creates and configures a new HTTP server instance.
func NewServer(props Server) *http.Server {
if props.Port == 0 {
props.Port = 8080
}
return &http.Server{
Addr: fmt.Sprintf(":%d", props.Port),
Handler: props.RegisterRoutes(props.Assets, props.Routes),
IdleTimeout: time.Minute,
ReadTimeout: time.Second * 10,
WriteTimeout: time.Second * 10,
}
}