Skip to content

Commit

Permalink
Issue umputun#31: Replace separate UI with the embedded HTMX based
Browse files Browse the repository at this point in the history
   - disabled FileServer Directory Listings
  • Loading branch information
oneils committed Aug 23, 2023
1 parent 8c3762a commit 1d5cd58
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions backend/app/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"context"
"html/template"
"net/http"
"path/filepath"
"strings"
"time"

Expand Down Expand Up @@ -96,22 +97,16 @@ func (s Server) routes() chi.Router {
return
}

if strings.HasPrefix(r.URL.Path, "/static") {
render.Status(r, http.StatusNotFound)
return
}

s.render(w, http.StatusNotFound, "404.tmpl.html", baseTmpl, "not found")
})

router.Get("/", s.indexCtrl)

router.Handle("/static", http.NotFoundHandler())
router.Post("/secure-link", s.generateLink)
router.Get("/message/{key}", s.showMessageView)
router.Post("/load-message", s.loadMessage)

// TODO: disable static directory listing
s.fileServer(router, "/", http.Dir(s.WebRoot))
s.fileServer(router, "/", truncatedFileSystem{http.Dir(s.WebRoot)})

return router
}
Expand Down Expand Up @@ -201,12 +196,40 @@ func (s Server) fileServer(r chi.Router, path string, root http.FileSystem) {
path += "*"

r.Get(path, func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/") && len(r.URL.Path) > 1 && r.URL.Path != "/static/" {
if strings.HasSuffix(r.URL.Path, "/") {
http.NotFound(w, r)
return
}
fs.ServeHTTP(w, r)
})

r.Handle("/static/*", http.StripPrefix("/static", fs))
r.Handle(path, http.StripPrefix("/static", fs))
}

// truncatedFileSystem is a wrapper for http.FileSystem to disable directory listings.
// It serves index.html for directories if present and return 404 for others
type truncatedFileSystem struct {
fs http.FileSystem
}

func (nfs truncatedFileSystem) Open(path string) (http.File, error) {
f, err := nfs.fs.Open(path)
if err != nil {
return nil, err
}

s, err := f.Stat()
if s.IsDir() {
index := filepath.Join(path, "index.html")
if _, err := nfs.fs.Open(index); err != nil {
closeErr := f.Close()
if closeErr != nil {
return nil, closeErr
}

return nil, err
}
}

return f, nil
}

0 comments on commit 1d5cd58

Please sign in to comment.