encapsulate notFoundHandler

This commit is contained in:
Hayden 2022-09-03 19:10:42 -08:00
parent 5bf7efe87e
commit 61483c3ea4

View file

@ -5,7 +5,6 @@ import (
"errors" "errors"
"fmt" "fmt"
"io" "io"
"io/fs"
"mime" "mime"
"net/http" "net/http"
"path" "path"
@ -26,14 +25,11 @@ const prefix = "/api"
// registerRoutes registers all the routes for the API // registerRoutes registers all the routes for the API
func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux { func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
registerMimes()
r := chi.NewRouter() r := chi.NewRouter()
a.setGlobalMiddleware(r) a.setGlobalMiddleware(r)
// =========================================================================
// Base Routes
DumpEmbedContents()
r.Get("/swagger/*", httpSwagger.Handler( r.Get("/swagger/*", httpSwagger.Handler(
httpSwagger.URL(fmt.Sprintf("%s://%s/swagger/doc.json", a.conf.Swagger.Scheme, a.conf.Swagger.Host)), httpSwagger.URL(fmt.Sprintf("%s://%s/swagger/doc.json", a.conf.Swagger.Scheme, a.conf.Swagger.Host)),
)) ))
@ -78,8 +74,7 @@ func (a *app) newRouter(repos *repo.AllRepos) *chi.Mux {
}) })
} }
r.NotFound(NotFoundHandler) r.NotFound(notFoundHandler())
return r return r
} }
@ -106,7 +101,7 @@ func (a *app) LogRoutes(r *chi.Mux) {
var ErrDir = errors.New("path is dir") var ErrDir = errors.New("path is dir")
func init() { func registerMimes() {
err := mime.AddExtensionType(".js", "application/javascript") err := mime.AddExtensionType(".js", "application/javascript")
if err != nil { if err != nil {
panic(err) panic(err)
@ -118,7 +113,8 @@ func init() {
} }
} }
func tryRead(fs embed.FS, prefix, requestedPath string, w http.ResponseWriter) error { func notFoundHandler() http.HandlerFunc {
tryRead := func(fs embed.FS, prefix, requestedPath string, w http.ResponseWriter) error {
f, err := fs.Open(path.Join(prefix, requestedPath)) f, err := fs.Open(path.Join(prefix, requestedPath))
if err != nil { if err != nil {
return err return err
@ -134,9 +130,9 @@ func tryRead(fs embed.FS, prefix, requestedPath string, w http.ResponseWriter) e
w.Header().Set("Content-Type", contentType) w.Header().Set("Content-Type", contentType)
_, err = io.Copy(w, f) _, err = io.Copy(w, f)
return err return err
} }
func NotFoundHandler(w http.ResponseWriter, r *http.Request) { return func(w http.ResponseWriter, r *http.Request) {
err := tryRead(public, "public", r.URL.Path, w) err := tryRead(public, "public", r.URL.Path, w)
if err == nil { if err == nil {
return return
@ -148,18 +144,5 @@ func NotFoundHandler(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
panic(err) panic(err)
} }
}
func DumpEmbedContents() {
// recursively prints all contents in the embed.FS
err := fs.WalkDir(public, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
fmt.Println(path)
return nil
})
if err != nil {
panic(err)
} }
} }