61 lines
1.5 KiB
Go
61 lines
1.5 KiB
Go
package web
|
|
|
|
import (
|
|
"mime"
|
|
"net/http"
|
|
"path"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
func (web *Web) indexHandler(entryPoint string) func(w http.ResponseWriter, r *http.Request) {
|
|
entryPoint = path.Clean(strings.TrimPrefix(entryPoint, "/"))
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
|
p := path.Clean(strings.TrimPrefix(r.URL.Path, "/"))
|
|
log.Debug().Str("path", p).Msg("requested path")
|
|
|
|
if web.box.Has(p) && !web.box.HasDir(p) {
|
|
f, err := web.box.Find(p)
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Error finding file")
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
write(w, f, p)
|
|
return
|
|
}
|
|
if web.box.HasDir(p) && web.box.Has(path.Join(p, "index.html")) {
|
|
f, err := web.box.Find(path.Join(p, "index.html"))
|
|
if err != nil {
|
|
log.Error().Err(err).Msg("Error finding file")
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
write(w, f, p)
|
|
return
|
|
}
|
|
|
|
log.Debug().Str("path", p).Str("entry", entryPoint).Msg("all handlers fell through, giving default")
|
|
if f, err := web.box.Find(entryPoint); err == nil {
|
|
write(w, f, p)
|
|
return
|
|
} else {
|
|
log.Error().AnErr("err", err).Msgf("could not load any files %s", err)
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
return fn
|
|
}
|
|
|
|
func write(w http.ResponseWriter, f []byte, path string) {
|
|
ctype := mime.TypeByExtension(filepath.Ext(path))
|
|
if ctype == "" {
|
|
ctype = http.DetectContentType(f)
|
|
}
|
|
if ctype != "" {
|
|
w.Header().Set("Content-Type", ctype)
|
|
}
|
|
w.Write(f)
|
|
}
|