Skip to content

Commit

Permalink
feat: add webui embedding
Browse files Browse the repository at this point in the history
  • Loading branch information
christophwitzko committed Feb 7, 2024
1 parent 92bc52c commit 2c88cc7
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
36 changes: 36 additions & 0 deletions pkg/webui/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package webui

import (
"errors"
"io/fs"
"net/http"
"path"
"strings"

webuifs "github.com/christophwitzko/wg-hub/webui"
)

func getWebuiFS() http.FileSystem {
s, err := fs.Sub(webuifs.FS, "out")
if err != nil {
panic(err)
}
return http.FS(s)
}

func getWebuiServer() http.HandlerFunc {
wfs := getWebuiFS()
fileServer := http.FileServer(wfs)
return func(w http.ResponseWriter, r *http.Request) {
rPath := path.Clean(r.URL.Path)
if !strings.HasSuffix(rPath, "/") {
_, err := wfs.Open(rPath)
// if the file does not exist, try to serve the html file
if errors.Is(err, fs.ErrNotExist) {
rPath += ".html"
r.URL.Path = rPath
}
}
fileServer.ServeHTTP(w, r)
}
}
3 changes: 1 addition & 2 deletions pkg/webui/webui.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,7 @@ func newServer(log *logrus.Logger, dev *device.Device, cfg *config.Config) *Serv
cfg: cfg,
api: api.NewAPIServer(log, dev, cfg),
}
fs := http.FileServer(http.Dir("webui/out"))
w.router.Get("/*", fs.ServeHTTP)
w.router.Get("/*", getWebuiServer())
w.router.Mount("/api", w.api)
return w
}
Expand Down
6 changes: 6 additions & 0 deletions webui/webui.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package webui

import "embed"

//go:embed out/*
var FS embed.FS

0 comments on commit 2c88cc7

Please sign in to comment.