57 lines
1.3 KiB
Go
57 lines
1.3 KiB
Go
package web
|
|
|
|
import (
|
|
"mime"
|
|
"net/http"
|
|
"path"
|
|
"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)
|
|
}
|
|
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
|
|
}
|
|
|
|
if f, err := web.box.Find(p); err != nil {
|
|
write(w, f, p)
|
|
return
|
|
}
|
|
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
return fn
|
|
}
|
|
|
|
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)
|
|
}
|