forked from ginuerzh/weedo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
filer.go
88 lines (75 loc) · 1.58 KB
/
filer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
// filer
package weedo
import (
"bytes"
"io"
"net/http"
"strings"
)
type File struct {
Id string `json:"fid"`
Name string `json:"name"`
}
type Dir struct {
Path string `json:"Directory"`
Files []*File
Subdirs []*File `json:"Subdirectories"`
}
func (dir Dir) String() string {
b := bytes.Buffer{}
b.WriteString("\n")
b.WriteString(dir.Path + "\n")
for _, d := range dir.Subdirs {
b.WriteString(" " + d.Name + "/\n")
}
for _, f := range dir.Files {
b.WriteString(" " + f.Name + "\n")
}
return b.String()
}
type Filer struct {
Url string
}
func NewFiler(url string) *Filer {
if !strings.HasPrefix(url, "http:") {
url = "http://" + url
}
return &Filer{
Url: url,
}
}
func (f *Filer) Dir(pathname string) (*Dir, error) {
if !strings.HasPrefix(pathname, "/") {
pathname = "/" + pathname
}
if !strings.HasSuffix(pathname, "/") {
pathname = pathname + "/"
}
resp, err := http.Get(f.Url + pathname)
if err != nil {
return nil, err
}
defer resp.Body.Close()
filerResp := new(Dir)
if err = decodeJson(resp.Body, filerResp); err != nil {
return nil, err
}
return filerResp, nil
}
func (f *Filer) Upload(pathname string, mimeType string, file io.Reader) error {
formData, contentType, err := makeFormData(pathname, mimeType, file)
if err != nil {
return err
}
if !strings.HasPrefix(pathname, "/") {
pathname = "/" + pathname
}
_, err = http.Post(f.Url+pathname, contentType, formData)
return err
}
func (f *Filer) Delete(pathname string) error {
if !strings.HasPrefix(pathname, "/") {
pathname = "/" + pathname
}
return del(f.Url + pathname)
}