-
Notifications
You must be signed in to change notification settings - Fork 4
/
files.go
86 lines (77 loc) · 2.17 KB
/
files.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
package mo2utils
import (
"context"
"fmt"
"io/ioutil"
"os"
"path"
"strings"
"github.com/Monkey-Mouse/mo2/mo2img"
"github.com/qiniu/go-sdk/v7/storage"
)
// ProcessAllFiles use handler function to process each file recursively under srcPath
func ProcessAllFiles(srcPath string, uploadRootPath string, processHandler func(parameter ...string)) {
if _, err := os.Stat(srcPath); os.IsNotExist(err) {
fmt.Println("Directory created")
} else {
processAllFiles(srcPath, srcPath, uploadRootPath, processHandler)
}
return
}
func processAllFiles(curPath string, rootPath string, uploadRootPath string, processHandler func(parameter ...string)) {
files, err := ioutil.ReadDir(curPath)
if err != nil {
panic(err)
}
for _, f := range files {
srcNewPath := path.Join(curPath, f.Name())
relativePath := strings.TrimPrefix(srcNewPath, rootPath)
uploadRelativePath := path.Join(uploadRootPath, relativePath)
if f.IsDir() {
processAllFiles(srcNewPath, rootPath, uploadRootPath, processHandler)
} else {
processHandler(srcNewPath, rootPath, uploadRelativePath)
}
}
}
// IsEnvRelease check if GIN_MODE is release
func IsEnvRelease() (release bool) {
return os.Getenv("GIN_MODE") == "release"
}
// UploadCDN upload frontend files to cdn
func UploadCDN() {
if IsEnvRelease() {
rootPath := "/home/dist"
uploadRootPath := "dist"
ProcessAllFiles(rootPath, uploadRootPath, func(parameter ...string) {
qiniuFile(parameter[0], parameter[2])
})
}
}
func qiniuFile(srcPath string, dstPath string) {
localFile := srcPath
key := dstPath
upToken := mo2img.GenerateOverwriteToken(localFile, dstPath)
cfg := storage.Config{}
// 空间对应的机房
cfg.Zone = &storage.ZoneHuanan
// 是否使用https域名
cfg.UseHTTPS = false
// 上传是否使用CDN上传加速
cfg.UseCdnDomains = false
// 构建表单上传的对象
formUploader := storage.NewFormUploader(&cfg)
ret := storage.PutRet{}
// 可选配置
/* putExtra := storage.PutExtra{
Params: map[string]string{
"x:name": "github logo",
},
}*/
err := formUploader.PutFile(context.Background(), &ret, upToken, key, localFile, nil)
if err != nil {
fmt.Println(err)
return
}
fmt.Println(ret.Key, ret.Hash)
}