-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathapp.go
76 lines (65 loc) · 1.87 KB
/
app.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
package main
import (
"html/template"
"io"
"net/http"
"os"
)
//Compile templates on start
var templates = template.Must(template.ParseFiles("tmpl/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":
display(w, "upload", nil)
//POST takes the uploaded file(s) and saves it to disk.
case "POST":
//parse the multipart form in the request
err := r.ParseMultipartForm(100000)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//get a ref to the parsed multipart form
m := r.MultipartForm
//get the *fileheaders
files := m.File["myfiles"]
for i, _ := range files {
//for each fileheader, get a handle to the actual file
file, err := files[i].Open()
defer file.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//create destination file making sure the path is writeable.
dst, err := os.Create("/home/sanat/" + files[i].Filename)
defer dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
//copy the uploaded file to the destination file
if _, err := io.Copy(dst, file); 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("assets"))))
//Listen on port 8080
http.ListenAndServe(":8080", nil)
}