cabinet/web/web_handlers.go

67 lines
1.5 KiB
Go

package web
import (
"io/ioutil"
"mime"
"net/http"
"os"
"path"
"path/filepath"
"github.com/rs/zerolog/log"
)
func (web *Web) indexHandler(entryPoint string) func(w http.ResponseWriter, r *http.Request) {
entryPoint = path.Join(path.Clean(entryPoint))
fn := func(w http.ResponseWriter, r *http.Request) {
p := path.Join(path.Clean(r.URL.Path))
log.Debug().Str("path", p).Msg("requested path")
var info os.FileInfo
f, err := web.static.Open(p)
if err != nil {
log.Error().Err(err).Msg("Error finding file")
goto entryPoint
}
defer f.Close()
info, err = f.Stat()
if err != nil {
log.Error().Err(err).Msg("Error finding file")
goto entryPoint
}
if info.IsDir() {
if f, err := web.static.Open(path.Join(p, "index.html")); err == nil && f != nil {
write(w, f, p)
return
} else {
log.Error().Msgf("Could not load file %s: %w", path.Join(p, "index.html"), err)
w.WriteHeader(http.StatusNotFound)
}
} else {
write(w, f, p)
return
}
entryPoint:
if f, err := web.static.Open(entryPoint); err == nil {
write(w, f, p)
return
} else {
log.Error().Msgf("Could not load file %s or %s", p, entryPoint)
w.WriteHeader(http.StatusNotFound)
}
}
return fn
}
func write(w http.ResponseWriter, file http.File, path string) {
f, _ := ioutil.ReadAll(file)
ctype := mime.TypeByExtension(filepath.Ext(path))
if ctype == "" {
ctype = http.DetectContentType(f)
}
if ctype != "" {
w.Header().Set("Content-Type", ctype)
}
w.Write(f)
}