major refactoring

This commit is contained in:
ston1th 2022-03-23 21:50:01 +01:00
commit 78b5e5f796
14 changed files with 712 additions and 576 deletions

View file

@ -6,6 +6,7 @@ import (
"errors"
"io"
stdfs "io/fs"
"math"
"net/http"
"path"
"strings"
@ -19,8 +20,16 @@ const (
csp = "Content-Security-Policy"
indexCSP = "default-src 'none';style-src 'unsafe-inline';frame-ancestors 'none'"
videoCSP = indexCSP + ";script-src 'sha256-ZLSc/s5/US9uVMMZOJ/yWiS1tj9nEoi+5Qoohy3QetU=';media-src 'self'"
gib = 1024 * 1024 * 1024
)
type data struct {
QuotaCur float64
QuotaMax float64
Paths dirContents
}
type FileServer struct {
log logr.Logger
fs *fs.FS
@ -32,7 +41,8 @@ func NewFileServer(fs *fs.FS, log logr.Logger) http.Handler {
}
func skipLog(path string) bool {
return strings.HasSuffix(path, "favicon.ico")
return path == "/?o=preloads" ||
strings.HasSuffix(path, "favicon.ico")
}
func (fs *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
@ -67,7 +77,7 @@ func (fs *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h := w.Header()
if option == "v" {
h.Set(csp, videoCSP)
err = video.Execute(w, r.URL.Path)
err = video.Execute(w, data{Paths: dirContents{Base: r.URL.Path}})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
@ -82,6 +92,10 @@ func (fs *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
fs.fs.CancelPreload(p)
}
rdir := "/"
if r.FormValue("r") == "preloads" {
http.Redirect(w, r, rdir+"?o=preloads", http.StatusFound)
return
}
if i := strings.LastIndex(p, "/"); i > 0 {
rdir = p[:i]
}
@ -97,7 +111,12 @@ func (fs *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
}
if option == "preloads" {
h.Set(csp, indexCSP)
err = preloads.Execute(w, getPreloads(p, fs.fs))
cur, max := fs.fs.QuotaUsage()
err = preloads.Execute(w, data{
QuotaCur: math.Round(float64(cur)/gib*100) / 100,
QuotaMax: float64(max) / gib,
Paths: getPreloads(p, fs.fs),
})
if err != nil {
fs.log.Error(err, "error rendering preloads")
http.Error(w, err.Error(), http.StatusInternalServerError)
@ -124,7 +143,7 @@ func (fs *FileServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.Set(csp, indexCSP)
w.WriteHeader(i.Status())
err = index.Execute(w, paths)
err = index.Execute(w, data{Paths: paths})
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return