-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStorageFile.go
81 lines (63 loc) · 1.68 KB
/
StorageFile.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
package UniStorage
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/Dereking/utils/StrUtil"
)
type StorageFile struct {
DataDir string
}
func NewStorageFile(dataDir string) *StorageFile {
return &StorageFile{DataDir: dataDir}
}
func (a *StorageFile) SaveURL(url, ext string) (filefullpath string, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
m := StrUtil.MD5(url)
filefullpath = fmt.Sprintf("%s%c%s%c%s%c%s%c%s%s",
a.DataDir, os.PathSeparator,
m[0:1], os.PathSeparator,
m[1:2], os.PathSeparator,
m[2:3], os.PathSeparator,
m, ext)
os.MkdirAll(filepath.Dir(filefullpath), 0755)
err = ioutil.WriteFile(filefullpath, data, 0755)
os.Chmod(filefullpath, 0755)
return
}
func (a *StorageFile) SaveObject(filename, ext string, obj interface{}) (filefullpath string, err error) {
data, _ := json.Marshal(obj)
m := StrUtil.MD5(filename)
filefullpath = fmt.Sprintf("%s%c%s%c%s%c%s%c%s%s",
a.DataDir, os.PathSeparator,
m[0:1], os.PathSeparator,
m[1:2], os.PathSeparator,
m[2:3], os.PathSeparator,
m, ext)
os.MkdirAll(filepath.Dir(filefullpath), 0755)
err = ioutil.WriteFile(filefullpath, data, 0755)
os.Chmod(filefullpath, 0755)
return
}
func (a *StorageFile) ReadObject(name, ext string) (data []byte, bExist bool, err error) {
bExist, filefullpath := a.ExistObject(name, ext)
if bExist {
data, err = ioutil.ReadFile(filefullpath)
}
return
}
func (a *StorageFile) ExistObject(name, ext string) (bExist bool, fullpath string) {
fullpath = IdToPath(name, a.DataDir, ext)
return PathExist(fullpath), fullpath
}