happy/web/web_handlers.go

57 lines
1.3 KiB
Go
Raw Permalink Normal View History

package web
import (
2019-10-31 14:34:23 +00:00
"mime"
"net/http"
"path"
2019-10-31 14:34:23 +00:00
"path/filepath"
"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 14:34:23 +00:00
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)
}
2019-10-31 14:34:23 +00:00
write(w, f, p)
return
}
if f, err := web.box.Find(p); err != nil {
2019-10-31 14:34:23 +00:00
write(w, f, p)
return
}
w.WriteHeader(http.StatusNotFound)
}
return fn
}
2019-10-31 14:34:23 +00:00
func write(w http.ResponseWriter, f []byte, path string) {
ctype := mime.TypeByExtension(filepath.Ext(path))
log.Debug().Msgf("detected type %s for %s by extension", ctype, path)
if ctype == "" {
ctype = http.DetectContentType(f)
log.Debug().Msgf("detected type %s for %s by content", ctype, path)
}
if ctype != "" {
w.Header().Set("Content-Type", ctype)
}
w.Write(f)
}