craban/server/web/web.go

54 lines
979 B
Go
Raw Normal View History

2021-09-11 23:32:07 +01:00
package web
import (
"embed"
2021-09-11 23:32:07 +01:00
"fmt"
"io/fs"
2021-09-11 23:32:07 +01:00
"net/http"
)
//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()
// 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) {
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()
}