2021-09-11 23:32:07 +01:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
2021-09-12 19:37:51 +01:00
|
|
|
"embed"
|
2021-09-11 23:32:07 +01:00
|
|
|
"fmt"
|
2021-09-12 19:37:51 +01:00
|
|
|
"io/fs"
|
2021-09-11 23:32:07 +01:00
|
|
|
"net/http"
|
|
|
|
)
|
|
|
|
|
2021-09-12 19:37:51 +01:00
|
|
|
//go:embed static/*
|
|
|
|
var staticFS embed.FS
|
|
|
|
var indexBytes []byte
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
indexBytes, _ = staticFS.ReadFile("static/index.html")
|
|
|
|
}
|
|
|
|
|
2021-09-12 17:27:49 +01:00
|
|
|
type WebServer struct {
|
|
|
|
*http.Server
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewWebServer(port int) (*WebServer, error) {
|
2021-09-11 23:32:07 +01:00
|
|
|
mux := http.NewServeMux()
|
|
|
|
|
2021-09-12 19:37:51 +01:00
|
|
|
// ToDo: register WS and API endpoints here
|
|
|
|
|
|
|
|
staticFSSub, _ := fs.Sub(staticFS, "static")
|
|
|
|
staticFileServerHandler := http.FileServer(http.FS(staticFSSub))
|
2021-09-11 23:32:07 +01:00
|
|
|
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
|
2021-09-12 19:37:51 +01:00
|
|
|
srw := &NotFoundIndexResponseWriter{ResponseWriter: w}
|
|
|
|
staticFileServerHandler.ServeHTTP(srw, r)
|
2021-09-11 23:32:07 +01:00
|
|
|
})
|
|
|
|
|
2021-09-12 17:27:49 +01:00
|
|
|
s := &WebServer{
|
|
|
|
&http.Server{
|
|
|
|
Addr: fmt.Sprintf(":%d", port),
|
|
|
|
Handler: mux,
|
|
|
|
},
|
2021-09-11 23:32:07 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return s, nil
|
|
|
|
}
|
2021-09-12 17:27:49 +01:00
|
|
|
|
|
|
|
func (w *WebServer) Start() error {
|
|
|
|
if err := w.Server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (w *WebServer) Close() error {
|
|
|
|
return w.Server.Close()
|
|
|
|
}
|