This commit is contained in:
Miguel de la Cruz 2021-09-12 21:57:59 +02:00
parent 68ae33e78a
commit f76aa74179
45 changed files with 6239 additions and 22 deletions

View file

@ -24,3 +24,12 @@ func (nfr *NotFoundIndexResponseWriter) Write(p []byte) (int, error) {
nfr.Header().Add("Content-Type", "text/html; charset=utf-8")
return nfr.ResponseWriter.Write(indexBytes)
}
type StaticFSHandler struct {
Handler http.Handler
}
func (s StaticFSHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
srw := &NotFoundIndexResponseWriter{ResponseWriter: w}
s.Handler.ServeHTTP(srw, r)
}

View file

@ -5,6 +5,11 @@ import (
"fmt"
"io/fs"
"net/http"
"git.ctrlz.es/mgdelacroix/craban/api"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
//go:embed static/*
@ -20,27 +25,32 @@ type WebServer struct {
}
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,
},
&http.Server{Addr: fmt.Sprintf(":%d", port)},
}
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")
staticFSHandler := StaticFSHandler{http.FileServer(http.FS(staticFSSub))}
r.PathPrefix("/").Handler(staticFSHandler)
// setup CORS only in the API subrouter?
originsOK := handlers.AllowedOrigins([]string{"*"})
methodsOK := handlers.AllowedMethods([]string{"GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS"})
w.Server.Handler = handlers.CORS(originsOK, methodsOK)(r)
}
func (w *WebServer) Start() error {
if err := w.Server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return err