/
upload.go
92 lines (78 loc) · 2.04 KB
/
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package main
import (
"github.com/neverlock/utility/httplog"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
)
//Compile templates on start
var templates = template.Must(template.ParseFiles("html/upload.html"))
//Display the named template
func display(w http.ResponseWriter, tmpl string, data interface{}) {
templates.ExecuteTemplate(w, tmpl+".html", data)
}
//This is where the action happens.
func uploadHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
//GET displays the upload form.
case "GET":
httplog.HttpLogln(r)
display(w, "upload", nil)
//POST takes the uploaded file(s) and saves it to disk.
case "POST":
//get the multipart reader for the request.
httplog.HttpLogln(r)
reader, err := r.MultipartReader()
// r.ParseMultipartForm(0)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//copy each part to destination.
for {
part, err := reader.NextPart()
if err == io.EOF {
break
}
if part.FormName() == "path" {
j, err := ioutil.ReadAll(part)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError) //do something
return
}
log.Println(string(j))
//log.Println(part)
}
//if part.FileName() is empty, skip this iteration.
if part.FileName() == "" {
continue
}
dst, err := os.Create("uploaded/" + part.FileName())
defer dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := io.Copy(dst, part); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
//display success message.
display(w, "upload", "Upload successful.")
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func main() {
http.HandleFunc("/upload", uploadHandler)
//static file handler.
http.Handle("/assets/", http.StripPrefix("/assets/", http.FileServer(http.Dir("uploaded"))))
//Listen on port 8080
bind := ":8080"
log.Printf("listening on %s...\n", bind)
http.ListenAndServe(bind, nil)
}