Skip to content

Commit

Permalink
No more chi, giving the default mux a chance
Browse files Browse the repository at this point in the history
  • Loading branch information
Bios-Marcel committed Dec 9, 2024
1 parent 21585c7 commit 2376646
Show file tree
Hide file tree
Showing 8 changed files with 45 additions and 52 deletions.
51 changes: 26 additions & 25 deletions cmd/scribblers/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,10 @@ import (
"os/signal"
"path"
"runtime/pprof"
"strings"
"syscall"
"time"

"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
"github.com/scribble-rs/scribble.rs/internal/api"
"github.com/scribble-rs/scribble.rs/internal/config"
Expand Down Expand Up @@ -40,28 +39,33 @@ func main() {
}
}

router := chi.NewMux()
router.Use(middleware.StripSlashes)
router.Use(middleware.Recoverer)
router.Use(cors.Handler(cors.Options{
router := http.NewServeMux()
corsWrapper := cors.Handler(cors.Options{
AllowedOrigins: cfg.CORS.AllowedOrigins,
AllowCredentials: cfg.CORS.AllowCredentials,
}))
})
register := func(method, path string, handler http.HandlerFunc) {
// Each path needs to start with a slash anyway, so this is convenient.
if !strings.HasPrefix(path, "/") {
path = "/" + path
}

log.Printf("Registering route: %s %s\n", method, path)
router.HandleFunc(fmt.Sprintf("%s %s", method, path), corsWrapper(handler).ServeHTTP)
}

// Healthcheck for deployments with monitoring if required.
router.Get(
"/"+path.Join(cfg.RootPath, "health"),
func(writer http.ResponseWriter, _ *http.Request) {
writer.WriteHeader(http.StatusOK)
})
register("GET", path.Join(cfg.RootPath, "health"), func(writer http.ResponseWriter, _ *http.Request) {
writer.WriteHeader(http.StatusOK)
})

api.NewHandler(cfg).SetupRoutes(cfg.RootPath, router)
api.NewHandler(cfg).SetupRoutes(cfg.RootPath, register)

frontendHandler, err := frontend.NewHandler(cfg)
if err != nil {
log.Fatal("error setting up frontend:", err)
}
frontendHandler.SetupRoutes(router)
frontendHandler.SetupRoutes(register)

if cfg.LobbyCleanup.Interval > 0 {
state.LaunchCleanupRoutine(cfg.LobbyCleanup)
Expand All @@ -81,21 +85,18 @@ func main() {
}
}()

for _, route := range router.Routes() {
log.Printf("Registered route: %s\n", route.Pattern)
if route.SubRoutes != nil {
for _, subRoute := range route.SubRoutes.Routes() {
log.Printf(" Registered route: %s\n", subRoute.Pattern)
}
}
}

address := fmt.Sprintf("%s:%d", cfg.NetworkAddress, cfg.Port)
log.Println("Started, listening on: http://" + address)

httpServer := &http.Server{
Addr: address,
Handler: router,
Addr: address,
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" && r.URL.Path[len(r.URL.Path)-1] == '/' {
r.URL.Path = r.URL.Path[:len(r.URL.Path)-1]
}

router.ServeHTTP(w, r)
}),
ReadHeaderTimeout: 10 * time.Second,
}
log.Fatalln(httpServer.ListenAndServe())
Expand Down
1 change: 0 additions & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ require (
github.com/Bios-Marcel/discordemojimap/v2 v2.0.6
github.com/Bios-Marcel/go-petname v0.0.1
github.com/caarlos0/env/v10 v10.0.0
github.com/go-chi/chi/v5 v5.1.0
github.com/go-chi/cors v1.2.1
github.com/gofrs/uuid/v5 v5.3.0
github.com/lxzan/gws v1.8.8
Expand Down
2 changes: 0 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dolthub/maphash v0.1.0 h1:bsQ7JsF4FkkWyrP3oCnFJgrCUAFbFf3kOl4L/QxPDyQ=
github.com/dolthub/maphash v0.1.0/go.mod h1:gkg4Ch4CdCDu5h6PMriVLawB7koZ+5ijb9puGMV50a4=
github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw=
github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8=
github.com/go-chi/cors v1.2.1 h1:xEC8UT3Rlp2QuWNEr4Fs/c2EAGVKBwy/1vHx3bppil4=
github.com/go-chi/cors v1.2.1/go.mod h1:sSbTewc+6wYHBBCW7ytsFSn836hqM7JxpglAy2Vzc58=
github.com/gofrs/uuid/v5 v5.3.0 h1:m0mUMr+oVYUdxpMLgSYCZiXe7PuVPnI94+OMeVBNedk=
Expand Down
19 changes: 9 additions & 10 deletions internal/api/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,27 @@ import (
"path"
"strings"

"github.com/go-chi/chi/v5"
"github.com/scribble-rs/scribble.rs/internal/metrics"
)

// SetupRoutes registers the /v1/ endpoints with the http package.
func (handler *V1Handler) SetupRoutes(rootPath string, router chi.Router) {
routePrefix := "/" + path.Join(rootPath, "v1")
func (handler *V1Handler) SetupRoutes(rootPath string, register func(string, string, http.HandlerFunc)) {
v1 := path.Join(rootPath, "v1")

metrics.SetupRoute(func(metricsHandler http.HandlerFunc) {
router.Get(routePrefix+"/metrics", metricsHandler)
register("GET", path.Join(v1, "metrics"), metricsHandler)
})
router.Get(routePrefix+"/stats", handler.getStats)
register("GET", path.Join(v1, "stats"), handler.getStats)

// These exist only for the public API. We version them in order to ensure
// backwards compatibility as far as possible.
router.Get(routePrefix+"/lobby", handler.getLobbies)
router.Post(routePrefix+"/lobby", handler.postLobby)
register("GET", path.Join(v1, "lobby"), handler.getLobbies)
register("POST", path.Join(v1, "lobby"), handler.postLobby)

router.Patch(routePrefix+"/lobby/{lobby_id}", handler.patchLobby)
register("PATCH", path.Join(v1, "lobby", "{lobby_id}"), handler.patchLobby)
// The websocket is shared between the public API and the official client
router.Get(routePrefix+"/lobby/{lobby_id}/ws", handler.websocketUpgrade)
router.Post(routePrefix+"/lobby/{lobby_id}/player", handler.postPlayer)
register("GET", path.Join(v1, "lobby", "{lobby_id}", "ws"), handler.websocketUpgrade)
register("POST", path.Join(v1, "lobby", "{lobby_id}", "player"), handler.postPlayer)
}

// remoteAddressToSimpleIP removes unnecessary clutter from the input,
Expand Down
5 changes: 2 additions & 3 deletions internal/api/v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import (
"net/http"
"strings"

"github.com/go-chi/chi/v5"
"github.com/gofrs/uuid/v5"
"github.com/mailru/easyjson"
"github.com/scribble-rs/scribble.rs/internal/config"
Expand Down Expand Up @@ -194,7 +193,7 @@ func (handler *V1Handler) postLobby(writer http.ResponseWriter, request *http.Re
}

func (handler *V1Handler) postPlayer(writer http.ResponseWriter, request *http.Request) {
lobby := state.GetLobby(chi.URLParam(request, "lobby_id"))
lobby := state.GetLobby(request.PathValue("lobby_id"))
if lobby == nil {
http.Error(writer, ErrLobbyNotExistent.Error(), http.StatusNotFound)
return
Expand Down Expand Up @@ -264,7 +263,7 @@ func (handler *V1Handler) patchLobby(writer http.ResponseWriter, request *http.R
return
}

lobby := state.GetLobby(chi.URLParam(request, "lobby_id"))
lobby := state.GetLobby(request.PathValue("lobby_id"))
if lobby == nil {
http.Error(writer, ErrLobbyNotExistent.Error(), http.StatusNotFound)
return
Expand Down
3 changes: 1 addition & 2 deletions internal/api/ws.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"runtime/debug"
"time"

"github.com/go-chi/chi/v5"
"github.com/gofrs/uuid/v5"
"github.com/lxzan/gws"
"github.com/mailru/easyjson"
Expand Down Expand Up @@ -44,7 +43,7 @@ func (handler *V1Handler) websocketUpgrade(writer http.ResponseWriter, request *
return
}

lobby := state.GetLobby(chi.URLParam(request, "lobby_id"))
lobby := state.GetLobby(request.PathValue("lobby_id"))
if lobby == nil {
http.Error(writer, ErrLobbyNotExistent.Error(), http.StatusNotFound)
return
Expand Down
13 changes: 6 additions & 7 deletions internal/frontend/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"net/http"
"path"

"github.com/go-chi/chi/v5"
"github.com/scribble-rs/scribble.rs/internal/translations"
)

Expand Down Expand Up @@ -49,12 +48,12 @@ type BasePageConfig struct {
}

// SetupRoutes registers the official webclient endpoints with the http package.
func (handler *SSRHandler) SetupRoutes(router chi.Router) {
router.Get("/"+handler.cfg.RootPath, handler.homePageHandler)
func (handler *SSRHandler) SetupRoutes(register func(string, string, http.HandlerFunc)) {
register("GET", handler.cfg.RootPath, handler.homePageHandler)

fileServer := http.FileServer(http.FS(frontendResourcesFS))
router.Get(
"/"+path.Join(handler.cfg.RootPath, "resources/*"),
register(
"GET", path.Join(handler.cfg.RootPath, "resources", "{file}"),
http.StripPrefix(
"/"+handler.cfg.RootPath,
http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
Expand All @@ -65,8 +64,8 @@ func (handler *SSRHandler) SetupRoutes(router chi.Router) {
}),
).ServeHTTP,
)
router.Get("/"+path.Join(handler.cfg.RootPath, "ssrEnterLobby/{lobby_id}"), handler.ssrEnterLobby)
router.Post("/"+path.Join(handler.cfg.RootPath, "ssrCreateLobby"), handler.ssrCreateLobby)
register("GET", path.Join(handler.cfg.RootPath, "ssrEnterLobby", "{lobby_id}"), handler.ssrEnterLobby)
register("POST", path.Join(handler.cfg.RootPath, "ssrCreateLobby"), handler.ssrCreateLobby)
}

// errorPageData represents the data that error.html requires to be displayed.
Expand Down
3 changes: 1 addition & 2 deletions internal/frontend/lobby.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"net/http"
"strings"

"github.com/go-chi/chi/v5"
"github.com/scribble-rs/scribble.rs/internal/api"
"github.com/scribble-rs/scribble.rs/internal/state"
"github.com/scribble-rs/scribble.rs/internal/translations"
Expand All @@ -27,7 +26,7 @@ type robotPageData struct {

// ssrEnterLobby opens a lobby, either opening it directly or asking for a lobby.
func (handler *SSRHandler) ssrEnterLobby(writer http.ResponseWriter, request *http.Request) {
lobby := state.GetLobby(chi.URLParam(request, "lobby_id"))
lobby := state.GetLobby(request.PathValue("lobby_id"))
if lobby == nil {
handler.userFacingError(writer, api.ErrLobbyNotExistent.Error())
return
Expand Down

0 comments on commit 2376646

Please sign in to comment.