cabinet/web/web_handlers.go

61 lines
1.5 KiB
Go
Raw Permalink Normal View History

2019-10-30 15:31:07 +00:00
package web
import (
2019-10-31 15:14:11 +00:00
"mime"
2019-10-30 15:31:07 +00:00
"net/http"
"path"
2019-10-31 15:14:11 +00:00
"path/filepath"
2019-11-01 17:09:17 +00:00
"strings"
2019-10-30 15:31:07 +00:00
"github.com/rs/zerolog/log"
)
func (web *Web) indexHandler(entryPoint string) func(w http.ResponseWriter, r *http.Request) {
2019-11-01 17:09:17 +00:00
entryPoint = path.Clean(strings.TrimPrefix(entryPoint, "/"))
2019-10-30 15:31:07 +00:00
fn := func(w http.ResponseWriter, r *http.Request) {
2019-11-01 17:09:17 +00:00
p := path.Clean(strings.TrimPrefix(r.URL.Path, "/"))
log.Debug().Str("path", p).Msg("requested path")
2019-10-30 15:31:07 +00:00
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)
}
2019-10-31 15:14:11 +00:00
write(w, f, p)
2019-10-30 15:31:07 +00:00
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)
}
2019-10-31 15:14:11 +00:00
write(w, f, p)
2019-10-30 15:31:07 +00:00
return
}
2019-11-01 17:09:17 +00:00
log.Debug().Str("path", p).Str("entry", entryPoint).Msg("all handlers fell through, giving default")
if f, err := web.box.Find(entryPoint); err == nil {
2019-10-31 15:14:11 +00:00
write(w, f, p)
2019-10-30 15:31:07 +00:00
return
2019-11-01 17:09:17 +00:00
} else {
log.Error().AnErr("err", err).Msgf("could not load any files %s", err)
2019-10-30 15:31:07 +00:00
}
w.WriteHeader(http.StatusNotFound)
}
return fn
}
2019-10-31 15:14:11 +00:00
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)
}