/
api.go
265 lines (227 loc) · 6.63 KB
/
api.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
package file
import (
"encoding/base64"
"fmt"
"io"
"mime/multipart"
"net/http"
"net/url"
"os"
"path"
"path/filepath"
"strings"
"sync"
"github.com/jery1024/fserver/web"
"github.com/jery1024/mlog"
)
var rootDistMap, fileDistMap sync.Map
func RegistRootDist(name, rootPath string) error {
if ret, ok := fileDistMap.Load(name); ok {
return fmt.Errorf("RegistFileDist failed with exist name, rootPath: %v", ret)
}
if name == "" {
return fmt.Errorf("RegistFileDist failed with invalid name, name: %v", name)
}
if rootPath == "" {
return fmt.Errorf("RegistFileDist failed with invalid rootPath, rootPath: %v", rootPath)
}
if !filepath.IsAbs(rootPath) {
if ret, err := filepath.Abs(rootPath); err != nil {
return fmt.Errorf("RegistFileDist failed with invalid rootPath, rootPath: %v, detail: %v", rootPath, err.Error())
} else {
rootPath = ret
}
}
rootDistMap.Store(name, rootPath)
// mlog.Infof("RegistRootDist successed, name: %v, rootPath: %v", name, rootPath)
return nil
}
func RegistFileDist(webPath, distPath string) error {
if ret, ok := fileDistMap.Load(webPath); ok {
return fmt.Errorf("RegistFileDist failed with exist webPath, distPath: %v", ret)
}
if webPath == "" {
return fmt.Errorf("RegistFileDist failed with invalid webPath, webPath: %v", webPath)
}
if distPath == "" {
return fmt.Errorf("RegistFileDist failed with invalid distPath, distPath: %v", distPath)
}
fileDistMap.Store(webPath, distPath)
// mlog.Infof("RegistFileDist successed, webPath: %v, distPath: %v", webPath, distPath)
return nil
}
func GetFileDist(webPath string) string {
if ret, ok := fileDistMap.Load(webPath); ok {
return fmt.Sprintf("%v", ret)
}
return ""
}
func GetRootDist(name string) string {
if ret, ok := rootDistMap.Load(name); ok {
return fmt.Sprintf("%v", ret)
}
return ""
}
/*
Title Download
router /download [post]
*/
func DownloadFile(w http.ResponseWriter, r *http.Request, params url.Values) error {
ret := struct {
Error string
}{}
web.ResponseOk(w, r, ret)
return nil
}
/*
Title Upload
router /upload [post]
base64Image: ""
uploadFiles: file(s)
*/
func UploadFile(w http.ResponseWriter, r *http.Request, params url.Values) error {
helper := &resUploadHelper{params: params, request: r, respwriter: w}
helper.verify()
// helper.saveImage()
helper.saveFileLocal()
return helper.result()
}
type resUploadHelper struct {
params url.Values
request *http.Request
respwriter http.ResponseWriter
imageName string
base64Image string
// single file
file multipart.File
fileHeader *multipart.FileHeader
// multi files
files []*multipart.FileHeader
fileList map[string]string
derr error
oerr string
}
func (p *resUploadHelper) verify() {
if p.derr != nil {
return
}
p.fileList = make(map[string]string, 0)
// p.imageName = p.params.Get("imageName")
// p.base64Image = p.params.Get("base64Image")
// if p.base64Image != "" {
// return
// }
// single file
file, fileHeader, err := p.request.FormFile("uploadFile")
if err != nil {
p.derr = fmt.Errorf("verify uploadFile failed, detail: %v", err.Error())
mlog.Errorf("MultipartForm.File: %+v", p.request.MultipartForm)
return
}
p.file = file
p.fileHeader = fileHeader
}
func (p *resUploadHelper) saveImage() {
if p.derr != nil || p.base64Image == "" {
return
}
sessID := web.SessionID(p.request)
// 验证是否为合法的图片内容
if !strings.Contains(p.imageName, ".") {
p.derr = fmt.Errorf("saveImage failed with unsupport image, imageName: %v", p.imageName)
return
}
imgDist := GetFileDist(p.request.URL.Path)
imgDist = strings.Replace(imgDist, "sessionID", sessID, -1)
filename := p.imageName
visitPath := path.Join(imgDist, filename)
// if ExistRes(filepath.Join(GetCurrentAbsPath(), "public", sessID, "dist", "img", filename)) {
if ExistRes(filepath.Join(imgDist, sessID, "img", filename)) {
p.fileList[visitPath] = filepath.Join(imgDist, sessID, "img", p.fileHeader.Filename)
return
}
saveImgFile := filepath.Join(imgDist, sessID, "img", filename)
if err := SaveForBase64(saveImgFile, p.base64Image); err != nil {
p.derr = fmt.Errorf("saveImage failed with invalid base64 image, base64Image: %v", p.base64Image)
return
}
p.fileList[visitPath] = filepath.Join(imgDist, sessID, "img", p.fileHeader.Filename)
}
func (p *resUploadHelper) saveFileLocal() {
if p.derr != nil || p.fileHeader == nil {
return
}
sessID := web.SessionID(p.request)
server := web.GetStatus(web.C_Status_Server, p.request).(*web.TServer)
rootDist := GetRootDist(server.Name)
fileDist := GetFileDist(p.request.URL.Path)
visitPath := path.Join(path.Base(rootDist), sessID, fileDist, p.fileHeader.Filename)
rootDist = filepath.Join(rootDist, sessID)
// if ExistRes(filepath.Join(GetCurrentAbsPath(), "public", sessID, "dsist/res", p.fileHeader.Filename)) {
if ExistRes(filepath.Join(rootDist, fileDist, p.fileHeader.Filename)) {
p.file.Close()
p.fileList[visitPath] = filepath.Join(rootDist, fileDist, p.fileHeader.Filename)
return
}
//create destination file making sure the path is writeable.
dst, err := os.Create(filepath.Join(rootDist, fileDist, p.fileHeader.Filename))
defer dst.Close()
if err != nil {
p.derr = fmt.Errorf("saveFileLocal failed while doing os.Create, detail: %v", err.Error())
return
}
//copy the uploaded file to the destination file
if _, err := io.Copy(dst, p.file); err != nil {
p.derr = fmt.Errorf("saveFileLocal failed while doing io.Copy, detail: %v", err.Error())
return
}
p.file.Close()
p.fileList[visitPath] = filepath.Join(rootDist, fileDist, p.fileHeader.Filename)
}
func (p *resUploadHelper) result() error {
ret := struct {
Error string
FileList map[string]string
}{}
if p.derr != nil {
mlog.Error(p.derr.Error())
ret.Error = "UploadFile failed"
if p.oerr != "" {
ret.Error = p.oerr
}
web.ResponseError(p.respwriter, p.request, ret.Error)
return p.derr
}
ret.FileList = p.fileList
web.ResponseOk(p.respwriter, p.request, ret)
return nil
}
func GetCurrentAbsPath() string {
dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return err.Error()
}
return strings.Replace(dir, "\\", "/", -1)
}
func ExistRes(fileOrPath string) bool {
_, err := os.Stat(fileOrPath)
return err == nil
}
func SaveForBase64(filePath, content string) error {
fullPath, err := filepath.Abs(filePath)
if err != nil {
return err
}
file, err := os.Create(fullPath)
if err != nil {
return fmt.Errorf("SaveToFile failed, filePath:%v, detail:%v", filePath, err.Error())
}
defer file.Close()
// decode by base64
contentBuf, base64Err := base64.StdEncoding.DecodeString(content)
if base64Err != nil {
return base64Err
}
_, err = file.Write(contentBuf)
return err
}