fixes and improvements in broker and render

This commit is contained in:
2025-05-23 14:31:23 +02:00
parent ba604bb8b4
commit 2fea2e6ac5
5 changed files with 116 additions and 94 deletions
+28
View File
@@ -2,7 +2,10 @@ package goblocks
import (
"net/http"
"os"
"path/filepath"
"slices"
"strings"
)
type Middleware func(http.Handler) http.Handler
@@ -35,6 +38,31 @@ func (r *Router) Group(fn func(r *Router)) {
fn(sub)
}
func (r *Router) Static(urlPrefix, dir string) {
urlPrefix = strings.TrimSuffix(urlPrefix, "/")
fileServer := http.FileServer(http.Dir(dir))
fs := http.StripPrefix(urlPrefix, http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
fullPath := filepath.Join(dir, req.URL.Path)
info, err := os.Stat(fullPath)
if err != nil {
http.NotFound(w, req)
return
}
if info.IsDir() {
http.NotFound(w, req)
return
}
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
fileServer.ServeHTTP(w, req)
}))
r.Handle(urlPrefix+"/", fs)
}
func (r *Router) HandleFunc(pattern string, h http.HandlerFunc) {
r.Handle(pattern, h)
}