Add common routines and theme dojigger

This commit is contained in:
Neale Pickett 2019-09-02 18:42:27 -06:00
parent 657a02e773
commit 54ea337447
2 changed files with 66 additions and 0 deletions

19
cmd/mothd/common.go Normal file
View File

@ -0,0 +1,19 @@
package main
import (
"path/filepath"
"strings"
)
func MothPath(base string, parts ...string) string {
path := filepath.Clean(filepath.Join(parts...))
parts = filepath.SplitList(path)
for i, part := range parts {
part = strings.TrimLeft(part, "./\\:")
parts[i] = part
}
parts = append([]string{base}, parts...)
path = filepath.Join(parts...)
path = filepath.Clean(path)
return path
}

47
cmd/mothd/theme.go Normal file
View File

@ -0,0 +1,47 @@
package main
import (
"net/http"
"os"
"strings"
)
type Theme struct {
ThemeDir string
}
func NewTheme(themeDir string) *Theme {
return &Theme{
ThemeDir: themeDir,
}
}
func (t *Theme) path(parts ...string) string {
return MothPath(t.ThemeDir, parts...)
}
func (t *Theme) staticHandler(w http.ResponseWriter, req *http.Request) {
path := req.URL.Path
if strings.Contains(path, "/.") {
http.Error(w, "Invalid URL path", http.StatusBadRequest)
return
}
if path == "/" {
path = "/index.html"
}
f, err := os.Open(t.path(path))
if err != nil {
http.NotFound(w, req)
return
}
defer f.Close()
d, err := f.Stat()
if err != nil {
http.NotFound(w, req)
return
}
http.ServeContent(w, req, path, d.ModTime(), f)
}