craban/server/web/web.go
Miguel de la Cruz f76aa74179 Stuff
2021-09-12 21:57:59 +02:00

63 lines
1.3 KiB
Go

package web
import (
"embed"
"fmt"
"io/fs"
"net/http"
"git.ctrlz.es/mgdelacroix/craban/api"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"
)
//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) {
s := &WebServer{
&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
}
return nil
}
func (w *WebServer) Close() error {
return w.Server.Close()
}