cabinet/web/web_handlers.go

55 lines
1.1 KiB
Go
Raw 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-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) {
fn := func(w http.ResponseWriter, r *http.Request) {
p := path.Clean(r.URL.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)
}
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
}
if f, err := web.box.Find(p); err != nil {
2019-10-31 15:14:11 +00:00
write(w, f, p)
2019-10-30 15:31:07 +00:00
return
}
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)
}