From e2ccf9717ca11bbcf8e9b8ee5332e3211d38cfa9 Mon Sep 17 00:00:00 2001 From: Wolfy-J Date: Thu, 7 Jun 2018 16:59:38 +0300 Subject: more tests --- _____/http/static.go | 68 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 _____/http/static.go (limited to '_____/http/static.go') diff --git a/_____/http/static.go b/_____/http/static.go new file mode 100644 index 00000000..b055099f --- /dev/null +++ b/_____/http/static.go @@ -0,0 +1,68 @@ +package http + +import ( + "github.com/sirupsen/logrus" + "net/http" + "os" + "path" + "path/filepath" + "strings" +) + +var forbiddenFiles = []string{".php", ".htaccess"} + +// staticServer serves static files +type staticServer struct { + root http.Dir +} + +// serve attempts to serve static file and returns true in case of success, will return false in case if file not +// found, not allowed or on read error. +func (svr *staticServer) serve(w http.ResponseWriter, r *http.Request) bool { + fpath := r.URL.Path + if !strings.HasPrefix(fpath, "/") { + fpath = "/" + fpath + } + fpath = path.Clean(fpath) + + if svr.forbidden(fpath) { + logrus.Warningf("attempt to access forbidden file %s", fpath) // todo: better logs + return false + } + + f, err := svr.root.Open(fpath) + if err != nil { + if !os.IsNotExist(err) { + logrus.Error(err) //todo: rr or access error + } + + return false + } + defer f.Close() + + d, err := f.Stat() + if err != nil { + logrus.Error(err) //todo: rr or access error + return false + } + + if d.IsDir() { + // do not serve directories + return false + } + + http.ServeContent(w, r, d.Name(), d.ModTime(), f) + return true +} + +// forbidden returns true if file has forbidden extension. +func (svr *staticServer) forbidden(path string) bool { + ext := strings.ToLower(filepath.Ext(path)) + for _, exl := range forbiddenFiles { + if ext == exl { + return true + } + } + + return false +} -- cgit v1.2.3