From 54ea337447d743f40e2a11fd2887175f08dbe8c3 Mon Sep 17 00:00:00 2001 From: Neale Pickett Date: Mon, 2 Sep 2019 18:42:27 -0600 Subject: [PATCH] Add common routines and theme dojigger --- cmd/mothd/common.go | 19 ++++++++++++++++++ cmd/mothd/theme.go | 47 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 66 insertions(+) create mode 100644 cmd/mothd/common.go create mode 100644 cmd/mothd/theme.go diff --git a/cmd/mothd/common.go b/cmd/mothd/common.go new file mode 100644 index 0000000..ca04486 --- /dev/null +++ b/cmd/mothd/common.go @@ -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 +} diff --git a/cmd/mothd/theme.go b/cmd/mothd/theme.go new file mode 100644 index 0000000..76eeb83 --- /dev/null +++ b/cmd/mothd/theme.go @@ -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) +}