Start refactoring to make code cleaner
This commit is contained in:
54
fileinfo.go
54
fileinfo.go
@@ -1,13 +1,17 @@
|
||||
package filemanager
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
)
|
||||
|
||||
// FileInfo is the info about a particular file or directory
|
||||
// FileInfo is the information about a particular file or directory
|
||||
type FileInfo struct {
|
||||
IsDir bool
|
||||
Name string
|
||||
@@ -15,6 +19,36 @@ type FileInfo struct {
|
||||
URL string
|
||||
ModTime time.Time
|
||||
Mode os.FileMode
|
||||
Path string
|
||||
}
|
||||
|
||||
// GetFileInfo gets the file information and, in case of error, returns the
|
||||
// respective HTTP error code
|
||||
func GetFileInfo(url *url.URL, c *Config) (*FileInfo, int, error) {
|
||||
var err error
|
||||
|
||||
path := strings.Replace(url.Path, c.BaseURL, c.PathScope, 1)
|
||||
path = filepath.Clean(path)
|
||||
|
||||
file := &FileInfo{Path: path}
|
||||
f, err := c.Root.Open(path)
|
||||
if err != nil {
|
||||
return file, ErrorToHTTPCode(err), err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
info, err := f.Stat()
|
||||
if err != nil {
|
||||
return file, ErrorToHTTPCode(err), err
|
||||
}
|
||||
|
||||
file.IsDir = info.IsDir()
|
||||
file.ModTime = info.ModTime()
|
||||
file.Name = info.Name()
|
||||
file.Size = info.Size()
|
||||
file.URL = url.Path
|
||||
|
||||
return file, 0, nil
|
||||
}
|
||||
|
||||
// HumanSize returns the size of the file as a human-readable string
|
||||
@@ -27,3 +61,21 @@ func (fi FileInfo) HumanSize() string {
|
||||
func (fi FileInfo) HumanModTime(format string) string {
|
||||
return fi.ModTime.Format(format)
|
||||
}
|
||||
|
||||
// Delete handles the delete requests
|
||||
func (fi FileInfo) Delete() (int, error) {
|
||||
var err error
|
||||
|
||||
// If it's a directory remove all the contents inside
|
||||
if fi.IsDir {
|
||||
err = os.RemoveAll(fi.Path)
|
||||
} else {
|
||||
err = os.Remove(fi.Path)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return ErrorToHTTPCode(err), err
|
||||
}
|
||||
|
||||
return http.StatusOK, nil
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user