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,38 +14,27 @@ import (
) )
func RouteServer(r chi.Router, cfg httpcfg.HttpCfg) { func RouteServer(r chi.Router, cfg httpcfg.HttpCfg) {
r.Group(func(r chi.Router) { r.Use(middleware.Logger)
filesDir := http.Dir(cfg.OtsStaticDir) r.Use(middleware.Recoverer)
r.Use(middleware.Logger) r.HandleFunc("/signatures/{hash}", triemap.HttpHandler(sigs.Both))
r.Use(middleware.Recoverer) r.HandleFunc("/topic0/{hash}", triemap.HttpHandler(topics.Both))
r.HandleFunc("/signatures/{hash}", triemap.HttpHandler(sigs.Both)) r.HandleFunc("/config.json", func(w http.ResponseWriter, r *http.Request) {
r.HandleFunc("/topic0/{hash}", triemap.HttpHandler(topics.Both)) json.NewEncoder(w).Encode(map[string]any{
r.HandleFunc("/config.json", func(w http.ResponseWriter, r *http.Request) { "erigonURL": cfg.OtsRpcDaemonUrl,
json.NewEncoder(w).Encode(map[string]any{ "beaconAPI": cfg.OtsBeaconApiUrl,
"erigonURL": cfg.OtsRpcDaemonUrl, "assetsURLPrefix": cfg.OtsExternalAssetUrl,
"beaconAPI": cfg.OtsBeaconApiUrl,
"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) {
if path != "/" && path[len(path)-1] != '/' { http.StripPrefix(r.RequestURI, fileServer).ServeHTTP(w, r)
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP) } else {
path += "/" fileServer.ServeHTTP(w, r)
} }
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";