embed ui files

This commit is contained in:
github-tijlxyz 2023-09-07 13:06:58 +02:00
parent e47ed79135
commit feee34b683
2 changed files with 35 additions and 1 deletions

View File

@ -1,8 +1,10 @@
package main package main
import ( import (
"embed"
"encoding/json" "encoding/json"
"net/http" "net/http"
"strings"
) )
func inviteDataApiHandler(w http.ResponseWriter, re *http.Request) { 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) 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
}
}

View File

@ -55,7 +55,7 @@ func main() {
// invitedata api // invitedata api
relay.Router().HandleFunc("/invitedata", inviteDataApiHandler) relay.Router().HandleFunc("/invitedata", inviteDataApiHandler)
// ui // ui
relay.Router().Handle("/", http.StripPrefix("/", http.FileServer(http.Dir("./ui/dist")))) relay.Router().HandleFunc("/", embeddedUIHandler)
fmt.Println("running on :3334") fmt.Println("running on :3334")
http.ListenAndServe(":3334", relay) http.ListenAndServe(":3334", relay)