craban/server/web/web.go
2021-09-12 20:37:51 +02:00

53 lines
979 B
Go

package web
import (
"embed"
"fmt"
"io/fs"
"net/http"
)
//go:embed static/*
var staticFS embed.FS
var indexBytes []byte
func init() {
indexBytes, _ = staticFS.ReadFile("static/index.html")
}
type WebServer struct {
*http.Server
}
func NewWebServer(port int) (*WebServer, error) {
mux := http.NewServeMux()
// ToDo: register WS and API endpoints here
staticFSSub, _ := fs.Sub(staticFS, "static")
staticFileServerHandler := http.FileServer(http.FS(staticFSSub))
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
srw := &NotFoundIndexResponseWriter{ResponseWriter: w}
staticFileServerHandler.ServeHTTP(srw, r)
})
s := &WebServer{
&http.Server{
Addr: fmt.Sprintf(":%d", port),
Handler: mux,
},
}
return s, nil
}
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()
}