2019-10-30 15:31:07 +00:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
2020-03-17 09:52:19 +00:00
|
|
|
"io/ioutil"
|
2019-10-31 15:14:11 +00:00
|
|
|
"mime"
|
2019-10-30 15:31:07 +00:00
|
|
|
"net/http"
|
2020-03-17 09:52:19 +00:00
|
|
|
"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) {
|
2020-03-17 09:52:19 +00:00
|
|
|
entryPoint = path.Join(path.Clean(entryPoint))
|
2019-10-30 15:31:07 +00:00
|
|
|
fn := func(w http.ResponseWriter, r *http.Request) {
|
2020-03-17 09:52:19 +00:00
|
|
|
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
|
|
|
|
2020-03-17 09:52:19 +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
|
|
|
}
|
2020-03-17 09:52:19 +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)
|
|
|
|
}
|
2020-03-17 09:52:19 +00:00
|
|
|
} else {
|
2019-10-31 15:14:11 +00:00
|
|
|
write(w, f, p)
|
2019-10-30 15:31:07 +00:00
|
|
|
return
|
|
|
|
}
|
2020-03-17 09:52:19 +00:00
|
|
|
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 {
|
2020-03-17 09:52:19 +00:00
|
|
|
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
|
|
|
|
2020-03-17 09:52:19 +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)
|
|
|
|
}
|