-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
executable file
·74 lines (67 loc) · 1.88 KB
/
main.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
package main
import (
"io"
"os"
"log"
"fmt"
"syscall"
"strings"
"net/http"
)
// 返回文件目录
func getFileInfo(file string) (fileName, filePath string) {
index := strings.LastIndex(file, "/")
return file[index + 1:], file[0:index + 1]
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method == "GET" {
io.WriteString(w, "<p>Hey <del>gays</del> guys, I'm ready for that, you know.</p>")
return
}
if r.Method == "POST" {
f, _, err := r.FormFile("file")
if err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
return
}
defer f.Close()
// to已经包含完整路径了
to := r.FormValue("to")
// 首先判断一遍目录是否存在
_, filePath := getFileInfo(to)
_, err = os.Open(filePath)
if err != nil && os.IsNotExist(err) {
// 错误都不处理了
oldMask := syscall.Umask(0)
os.MkdirAll(filePath, os.ModePerm)
syscall.Umask(oldMask)
}
t, err := os.Create(to)
if err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
return
}
defer t.Close()
if _, err := io.Copy(t, f); err != nil {
http.Error(w, err.Error(),
http.StatusInternalServerError)
return
}
fmt.Println(r.FormValue("to"))
// success
io.WriteString(w, "0")
}
}
func main () {
port := "8527"
if len(os.Args) == 2 {
port = os.Args[1]
}
http.HandleFunc("/", uploadHandler)
err := http.ListenAndServe(":" + port, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err.Error())
}
}