craban/server/web/web.go

70 lines
1.8 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"
"github.com/rs/zerolog/log"
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", api.Login).Methods("POST")
apiRouter.HandleFunc("/users", api.Secured(api.CreateUser)).Methods("POST")
apiRouter.HandleFunc("/games", api.Secured(api.CreateGame)).Methods("POST")
apiRouter.HandleFunc("/games", api.Secured(api.ListGames)).Methods("GET")
apiRouter.HandleFunc("/games/{id:[0-9]+}", api.Secured(api.GetGame)).Methods("GET")
apiRouter.HandleFunc("/games/{id:[0-9]+}/post", api.Secured(api.CreatePostForGame)).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 {
log.Debug().Msg("starting webserver")
2021-09-12 17:27:49 +01:00
if err := w.Server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
return err
}
return nil
}
func (w *WebServer) Close() error {
log.Debug().Msg("closing webserver")
2021-09-12 17:27:49 +01:00
return w.Server.Close()
}