cabinet/web/web_handlers.go

67 lines
1.5 KiB
Go
Raw Normal View History

2019-10-30 15:31:07 +00:00
package web
import (
"io/ioutil"
2019-10-31 15:14:11 +00:00
"mime"
2019-10-30 15:31:07 +00:00
"net/http"
"os"
2019-10-30 15:31:07 +00:00
"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) {
entryPoint = path.Join(path.Clean(entryPoint))
2019-10-30 15:31:07 +00:00
fn := func(w http.ResponseWriter, r *http.Request) {
p := path.Join(path.Clean(r.URL.Path))
2019-11-01 17:09:17 +00:00
log.Debug().Str("path", p).Msg("requested path")
2019-10-30 15:31:07 +00:00
var info os.FileInfo
f, err := web.static.Open(p)
if err != nil {
log.Error().Err(err).Msg("Error finding file")
goto entryPoint
2019-10-30 15:31:07 +00:00
}
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)
2019-10-30 15:31:07 +00:00
w.WriteHeader(http.StatusNotFound)
}
} else {
2019-10-31 15:14:11 +00:00
write(w, f, p)
2019-10-30 15:31:07 +00:00
return
}
entryPoint:
if f, err := web.static.Open(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().Msgf("Could not load file %s or %s", p, entryPoint)
w.WriteHeader(http.StatusNotFound)
2019-10-30 15:31:07 +00:00
}
}
return fn
}
2019-10-31 15:14:11 +00:00
func write(w http.ResponseWriter, file http.File, path string) {
f, _ := ioutil.ReadAll(file)
2019-10-31 15:14:11 +00:00
ctype := mime.TypeByExtension(filepath.Ext(path))
if ctype == "" {
ctype = http.DetectContentType(f)
}
if ctype != "" {
w.Header().Set("Content-Type", ctype)
}
w.Write(f)
}