-
-
Notifications
You must be signed in to change notification settings - Fork 129
/
Copy pathmain.go
68 lines (56 loc) · 1.49 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
package main
import (
"fmt"
"io"
"net/http"
"os"
"text/template"
)
// Compile templates on start of the application
var templates = template.Must(template.ParseFiles("public/upload.html"))
// Display the named template
func display(w http.ResponseWriter, page string, data interface{}) {
templates.ExecuteTemplate(w, page+".html", data)
}
func uploadFile(w http.ResponseWriter, r *http.Request) {
// Maximum upload of 10 MB files
r.ParseMultipartForm(10 << 20)
// Get handler for filename, size and headers
file, handler, err := r.FormFile("myFile")
if err != nil {
fmt.Println("Error Retrieving the File")
fmt.Println(err)
return
}
defer file.Close()
fmt.Printf("Uploaded File: %+v\n", handler.Filename)
fmt.Printf("File Size: %+v\n", handler.Size)
fmt.Printf("MIME Header: %+v\n", handler.Header)
// Create file
dst, err := os.Create(handler.Filename)
defer dst.Close()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// Copy the uploaded file to the created file on the filesystem
if _, err := io.Copy(dst, file); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Successfully Uploaded File\n")
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
display(w, "upload", nil)
case "POST":
uploadFile(w, r)
}
}
func main() {
// Upload route
http.HandleFunc("/upload", uploadHandler)
//Listen on port 8080
http.ListenAndServe(":8080", nil)
}