alice-lg/ui/assets.go

46 lines
1003 B
Go
Raw Permalink Normal View History

2022-01-21 19:38:54 +01:00
package ui
import (
"embed"
"net/http"
"net/url"
2022-07-25 18:48:19 +02:00
"path"
2022-01-21 19:38:54 +01:00
"strings"
)
// Assets hold the alice-lg frontend build
//go:embed build/*
var Assets embed.FS
// AssetsHTTPHandler handles HTTP request at a specific prefix.
// The prefix is usually /static.
func AssetsHTTPHandler(prefix string) http.Handler {
handler := http.FileServer(http.FS(Assets))
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
2022-07-25 18:48:19 +02:00
reqPath := req.URL.Path
2022-01-21 19:38:54 +01:00
rawPath := req.URL.RawPath
2022-07-25 18:48:19 +02:00
if !strings.HasPrefix(reqPath, prefix) {
2022-01-21 19:38:54 +01:00
handler.ServeHTTP(res, req)
return
}
// Rewrite path
2022-07-25 18:48:19 +02:00
reqPath = path.Join("build/", reqPath)
rawPath = path.Join("build/", rawPath)
2022-01-21 19:38:54 +01:00
// This is pretty much like the StripPrefix middleware,
// from net/http, however we replace the prefix with `build/`.
req1 := new(http.Request)
*req1 = *req // clone request
req1.URL = new(url.URL)
*req1.URL = *req.URL
2022-07-25 18:48:19 +02:00
req1.URL.Path = reqPath
2022-01-21 19:38:54 +01:00
req1.URL.RawPath = rawPath
handler.ServeHTTP(res, req1)
})
}