use go embed

This commit is contained in:
Annika Hannig 2021-03-22 15:41:36 +01:00
parent 2e48e42795
commit c5f459329e
No known key found for this signature in database
GPG Key ID: 62E226E47DDCE58D
5 changed files with 61 additions and 15 deletions

View File

@ -37,14 +37,12 @@ func webPrepareClientHTML(html string) string {
func webRegisterAssets(ui UiConfig, router *httprouter.Router) error {
log.Println("Preparing and installing assets")
// Serve static assets
assetsHandler := http.StripPrefix("/static/", http.FileServer(client.Assets))
// Prepare client html: Rewrite paths
indexHTML, err := assets.ReadFile("index.html")
indexHTMLData, err := client.Assets.ReadFile("build/index.html")
if err != nil {
return err
}
indexHTML := string(indexHTMLData) // TODO: migrate to []byte
theme := NewTheme(ui.Theme)
err = theme.RegisterThemeAssets(router)
@ -56,7 +54,7 @@ func webRegisterAssets(ui UiConfig, router *httprouter.Router) error {
indexHTML = webPrepareClientHTML(indexHTML)
// Register static assets
router.Handler("GET", "/static/*path", assetsHandler)
router.Handler("GET", "/static/*path", client.AssetsHTTPHandler("/static"))
// Rewrite paths
// Serve index html as root...

44
client/assets.go Normal file
View File

@ -0,0 +1,44 @@
package client
import (
"embed"
"net/http"
"net/url"
"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) {
path := req.URL.Path
rawPath := req.URL.RawPath
if !strings.HasPrefix(path, prefix) {
handler.ServeHTTP(res, req)
return
}
// Rewrite path
path = "build/" + strings.TrimPrefix(path, prefix)
rawPath = "build/" + strings.TrimPrefix(rawPath, prefix)
// 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
req1.URL.Path = path
req1.URL.RawPath = rawPath
handler.ServeHTTP(res, req1)
})
}

13
client/assets_test.go Normal file
View File

@ -0,0 +1,13 @@
package client
import (
"testing"
)
func TestPresenceOfIndexHTML(t *testing.T) {
content, err := Assets.ReadFile("build/index.html")
if err != nil {
t.Fatal(err)
}
t.Log(string(content))
}

View File

@ -1,9 +0,0 @@
package client
import (
"embed"
)
// Assets hold the alice-lg frontend build
//go:embed build/*
var Assets embed.FS

2
go.mod
View File

@ -1,6 +1,6 @@
module github.com/alice-lg/alice-lg
go 1.14
go 1.16
require (
github.com/GeertJohan/go.rice v1.0.2