From feee34b68388a6fad44c4a61bf44adf4dedd013a Mon Sep 17 00:00:00 2001 From: github-tijlxyz <123159729+github-tijlxyz@users.noreply.github.com> Date: Thu, 7 Sep 2023 13:06:58 +0200 Subject: [PATCH] embed ui files --- handler.go | 34 ++++++++++++++++++++++++++++++++++ main.go | 2 +- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/handler.go b/handler.go index 908e50a..5c05cb4 100644 --- a/handler.go +++ b/handler.go @@ -1,8 +1,10 @@ package main import ( + "embed" "encoding/json" "net/http" + "strings" ) func inviteDataApiHandler(w http.ResponseWriter, re *http.Request) { @@ -18,3 +20,35 @@ func inviteDataApiHandler(w http.ResponseWriter, re *http.Request) { http.Error(w, "internal server error", http.StatusInternalServerError) } } + +// embed ui files +//go:embed ui/dist/* +var uiContent embed.FS + +func embeddedUIHandler(w http.ResponseWriter, r *http.Request) { + path := "ui/dist" + r.URL.Path + + if r.URL.Path == "/" { + path = "ui/dist/index.html" + } + + data, err := uiContent.ReadFile(path) + if err != nil { + http.Error(w, http.StatusText(http.StatusNotFound), http.StatusNotFound) + return + } + + contentType := http.DetectContentType(data) + if strings.HasSuffix(r.URL.Path, ".js") { + contentType = "application/javascript" + } else if strings.HasSuffix(r.URL.Path, ".css") { + contentType = "text/css" + } + + w.Header().Set("Content-Type", contentType) + + if _, err := w.Write(data); err != nil { + http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) + return + } +} diff --git a/main.go b/main.go index 1ffcc69..effe18e 100644 --- a/main.go +++ b/main.go @@ -55,7 +55,7 @@ func main() { // invitedata api relay.Router().HandleFunc("/invitedata", inviteDataApiHandler) // ui - relay.Router().Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./ui/dist")))) + relay.Router().HandleFunc("/", embeddedUIHandler) fmt.Println("running on :3334") http.ListenAndServe(":3334", relay)