Migrate to go embed

This commit is contained in:
Jannis Mattheis
2021-11-29 19:02:35 +01:00
parent 15349b9294
commit 557c1eba6b
4 changed files with 26 additions and 31 deletions
-1
View File
@@ -4,7 +4,6 @@ project_name: screego
before:
hooks:
- go mod download
- go run hack/packr/packr.go
builds:
- env:
- CGO_ENABLED=0
-8
View File
@@ -88,14 +88,6 @@ $ golangci-lint run
$ (cd ui && yarn build)
```
1. Generate static assets for go.
Run [packr](https://github.com/gobuffalo/packr) (embeds static assets in go binaries)
```bash
$ go run hack/packr/packr.go
```
1. Build the binary
```bash
CGO_ENABLED=0 go build \
-7
View File
@@ -1,7 +0,0 @@
package main
import "github.com/gobuffalo/packr/v2/packr2/cmd"
func main() {
cmd.Execute()
}
+26 -15
View File
@@ -1,38 +1,49 @@
package ui
import (
"embed"
"fmt"
"io/fs"
"io/ioutil"
"net/http"
"github.com/gobuffalo/packr/v2"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
)
var box = packr.New("ui", "build/")
//go:embed build
var buildFiles embed.FS
var files, _ = fs.Sub(buildFiles, "build")
// Register registers the ui on the root path.
func Register(r *mux.Router) {
r.Handle("/", serveFile("index.html", "text/html", box))
r.Handle("/index.html", serveFile("index.html", "text/html", box))
r.Handle("/manifest.json", serveFile("manifest.json", "application/json", box))
r.Handle("/service-worker.js", serveFile("service-worker.js", "text/javascript", box))
r.Handle("/assets-manifest.json", serveFile("asserts-manifest.json", "application/json", box))
r.Handle("/static/{type}/{resource}", http.FileServer(box))
r.Handle("/", serveFile("index.html", "text/html"))
r.Handle("/index.html", serveFile("index.html", "text/html"))
r.Handle("/service-worker.js", serveFile("service-worker.js", "text/javascript"))
r.Handle("/assets-manifest.json", serveFile("asserts-manifest.json", "application/json"))
r.Handle("/static/{type}/{resource}", http.FileServer(http.FS(files)))
r.Handle("/favicon.ico", serveFile("favicon.ico", "image/x-icon", box))
r.Handle("/favicon.ico", serveFile("favicon.ico", "image/x-icon"))
for _, size := range []string{"16x16", "32x32", "192x192", "256x256"} {
fileName := fmt.Sprintf("/favicon-%s.png", size)
r.Handle(fileName, serveFile(fileName, "image/png", box))
r.Handle(fileName, serveFile(fileName, "image/png"))
}
}
func serveFile(name, contentType string, box *packr.Box) http.HandlerFunc {
func serveFile(name, contentType string) http.HandlerFunc {
file, err := files.Open(name)
if err != nil {
log.Panic().Err(err).Msgf("could not find %s", file)
}
defer file.Close()
content, err := ioutil.ReadAll(file)
if err != nil {
log.Panic().Err(err).Msgf("could not read %s", file)
}
return func(writer http.ResponseWriter, reg *http.Request) {
writer.Header().Set("Content-Type", contentType)
content, err := box.Find(name)
if err != nil {
panic(err)
}
_, _ = writer.Write(content)
}
}