diff options
author | Wolfy-J <[email protected]> | 2018-06-05 16:23:14 +0300 |
---|---|---|
committer | Wolfy-J <[email protected]> | 2018-06-05 16:23:14 +0300 |
commit | 76ff8d1c95e087749d559ee5a4f8f0348feafffa (patch) | |
tree | 112630d2d2cfe41d809065034c13b1066b8e05c2 /cmd/_____/http/static.go | |
parent | 3c86132f90ef6473b4073a8b1500d01b6114fc30 (diff) |
Cs and refactoring
Diffstat (limited to 'cmd/_____/http/static.go')
-rw-r--r-- | cmd/_____/http/static.go | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/cmd/_____/http/static.go b/cmd/_____/http/static.go new file mode 100644 index 00000000..d7030c3f --- /dev/null +++ b/cmd/_____/http/static.go @@ -0,0 +1,70 @@ +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 +} |