-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathhttp_upload.go
75 lines (66 loc) · 1.57 KB
/
http_upload.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
package main
import (
"io"
"mime/multipart"
"net/http"
"os"
"path/filepath"
)
func uploadHandler(w http.ResponseWriter, r *http.Request) httpResult {
if isLocalhost(r) {
return httpResult{Status: http.StatusForbidden}
}
if err := r.ParseMultipartForm(100 << 20); err != nil {
return httpResult{Status: http.StatusBadRequest, Error: err}
}
multipartFile := func(key string) *multipart.FileHeader {
if r.MultipartForm == nil {
return nil
}
vs := r.MultipartForm.File[key]
if len(vs) == 0 {
return nil
}
return vs[0]
}
multipartValue := func(key string) string {
if r.MultipartForm == nil {
return ""
}
vs := r.MultipartForm.Value[key]
if len(vs) == 0 {
return ""
}
return vs[0]
}
prefix := getPathPrefix(r)
root := fromURLPath(multipartValue("root"), prefix)
path := filepath.Join(root, filepath.FromSlash(multipartValue("path")))
file, err := multipartFile("file").Open()
if err != nil {
return httpResult{Error: err}
}
defer file.Close()
if fi, err := os.Stat(root); err != nil {
return httpResult{Error: err}
} else if !fi.IsDir() {
return httpResult{Status: http.StatusForbidden}
}
if err := os.MkdirAll(filepath.Dir(path), 0777); err != nil {
return httpResult{Error: err}
}
dest, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
return httpResult{Error: err}
}
defer dest.Close()
_, err = io.Copy(dest, file)
if err != nil {
return httpResult{Error: err}
}
err = dest.Close()
if err != nil {
return httpResult{Error: err}
}
return httpResult{Status: http.StatusOK}
}