craban/server/web/web.go

64 lines
1.3 KiB
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"
2021-09-12 20:57:59 +01:00
"git.ctrlz.es/mgdelacroix/craban/api"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
2021-09-11 23:32:07 +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-12 20:57:59 +01:00
s := &WebServer{
&http.Server{Addr: fmt.Sprintf(":%d", port)},
}
2021-09-11 23:32:07 +01:00
2021-09-12 20:57:59 +01:00
return s, nil
}
func (w *WebServer) RegisterRoutes(api *api.API) {
r := mux.NewRouter()
apiRouter := r.PathPrefix("/api").Subrouter()
apiRouter.HandleFunc("/login", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "SAMPLE TOKEN")
}).Methods("POST")
staticFSSub, _ := fs.Sub(staticFS, "static")
2021-09-12 20:57:59 +01:00
staticFSHandler := StaticFSHandler{http.FileServer(http.FS(staticFSSub))}
r.PathPrefix("/").Handler(staticFSHandler)
2021-09-11 23:32:07 +01:00
2021-09-12 20:57:59 +01:00
// setup CORS only in the API subrouter?
originsOK := handlers.AllowedOrigins([]string{"*"})
methodsOK := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})
2021-09-11 23:32:07 +01:00
2021-09-12 20:57:59 +01:00
w.Server.Handler = handlers.CORS(originsOK, methodsOK)(r)
2021-09-11 23:32:07 +01:00
}
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()
}