redo server routing to be simpler

This commit is contained in:
a 2022-10-25 16:54:28 -05:00
parent 9807b21fd3
commit 9f2de2de97
2 changed files with 21 additions and 32 deletions

View File

@ -3,7 +3,7 @@ package main
import ( import (
"encoding/json" "encoding/json"
"net/http" "net/http"
"strings" "os"
"gfx.cafe/open/4bytes/sigs" "gfx.cafe/open/4bytes/sigs"
"gfx.cafe/open/4bytes/topics" "gfx.cafe/open/4bytes/topics"
@ -14,8 +14,6 @@ import (
) )
func RouteServer(r chi.Router, cfg httpcfg.HttpCfg) { func RouteServer(r chi.Router, cfg httpcfg.HttpCfg) {
r.Group(func(r chi.Router) {
filesDir := http.Dir(cfg.OtsStaticDir)
r.Use(middleware.Logger) r.Use(middleware.Logger)
r.Use(middleware.Recoverer) r.Use(middleware.Recoverer)
r.HandleFunc("/signatures/{hash}", triemap.HttpHandler(sigs.Both)) r.HandleFunc("/signatures/{hash}", triemap.HttpHandler(sigs.Both))
@ -27,25 +25,16 @@ func RouteServer(r chi.Router, cfg httpcfg.HttpCfg) {
"assetsURLPrefix": cfg.OtsExternalAssetUrl, "assetsURLPrefix": cfg.OtsExternalAssetUrl,
}) })
}) })
FileServer(r, "/", filesDir)
})
}
// FileServer conveniently sets up a http.FileServer handler to serve filesDir := http.Dir(cfg.OtsStaticDir)
// static files from a http.FileSystem. fileServer := http.FileServer(filesDir)
func FileServer(r chi.Router, path string, root http.FileSystem) { r.Handle("/*", http.StripPrefix("/", fileServer))
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit any URL parameters.") r.Get("/*", func(w http.ResponseWriter, r *http.Request) {
if _, err := os.Stat(cfg.OtsStaticDir + r.RequestURI); os.IsNotExist(err) {
http.StripPrefix(r.RequestURI, fileServer).ServeHTTP(w, r)
} else {
fileServer.ServeHTTP(w, r)
} }
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, func(w http.ResponseWriter, r *http.Request) {
rctx := chi.RouteContext(r.Context())
pathPrefix := strings.TrimSuffix(rctx.RoutePattern(), "/*")
fs := http.StripPrefix(pathPrefix, http.FileServer(root))
fs.ServeHTTP(w, r)
}) })
} }

View File

@ -1,5 +1,5 @@
import React, { Suspense } from "react"; import React, { Suspense } from "react";
import { HashRouter as Router, Routes, Route } from "react-router-dom"; import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import WarningHeader from "./WarningHeader"; import WarningHeader from "./WarningHeader";
import Home from "./Home"; import Home from "./Home";
import Main from "./Main"; import Main from "./Main";