-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloverbox.go
75 lines (63 loc) · 1.54 KB
/
cloverbox.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 (
"flag"
"io"
"net/http"
"os"
"path/filepath"
"strconv"
)
func main() {
port := flag.Int("port", 8080, "Port to listen on")
flag.Parse()
http.Handle("/", http.FileServer(http.Dir("public/")))
http.HandleFunc("/upload", uploadHandler)
err := http.ListenAndServe(":" + strconv.Itoa(*port), nil)
if err != nil {
panic(err)
}
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Redirect(w, r, "/", http.StatusSeeOther)
return
}
err := r.ParseMultipartForm(10 << 20) //maximum of 10MB
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//get the file from the request
file, handler, err := r.FormFile("uploadfile")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer file.Close()
//determine what folder to put the file in
var folder string
ext := filepath.Ext(handler.Filename)
switch ext {
case ".png":
folder = "images/"
case ".ogg":
folder = "sound/"
default:
return //file type not supported
}
//check if the file exists
if _, err := os.Stat("public/" + folder + handler.Filename); err == nil {
http.Error(w, "File already exists", http.StatusInternalServerError)
return
}
//write the file to the filesystem
fileName := "public/" + folder + handler.Filename
f, err := os.OpenFile(fileName, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer f.Close()
io.Copy(f, file)
w.Write([]byte("ok"))
}