package wrouter import ( "io" "mime" "net/http" "os" "path" "strings" "git.aiterp.net/gisle/wrouter/response" "git.aiterp.net/gisle/wrouter/auth" ) type Static struct { path string } func NewStatic(path string) *Static { return &Static{path} } func (static *Static) Handle(urlPath string, w http.ResponseWriter, req *http.Request, user *auth.User) bool { // Get the subpath out of the path subpath := req.URL.Path[len(urlPath):] if subpath[0] == '/' { subpath = subpath[1:] } // Disallow breaking out of the folder if strings.Contains(subpath, "..") { response.Text(w, 403, "No .. in paths allowed") return true } // Try loading the file filepath := path.Join(static.path, subpath) info, err := os.Stat(filepath) if err != nil || info.IsDir() { return false } file, err := os.Open(filepath) if err != nil || file == nil { return false } // Find and convert extension ep := strings.LastIndex(filepath, ".") ext := "" if ep != -1 { ext = filepath[ep:] } mimeType := mime.TypeByExtension(ext) if mimeType == "" { mimeType = "text/plain" } w.Header().Set("Content-Type", mimeType) // Submit w.WriteHeader(200) io.Copy(w, file) return true }