forked from filipenos/serving
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
81 lines (69 loc) · 1.74 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
75
76
77
78
79
80
81
package main
import (
"flag"
"fmt"
"html/template"
"io"
"log"
"net/http"
"os"
)
var (
port, down, up string
)
func init() {
pwd, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
flag.StringVar(&port, "port", "8080", "Serve port number")
flag.StringVar(&down, "download-dir", pwd, "Directory to be served")
flag.StringVar(&up, "upload-dir", pwd, "Directory to upload files")
}
func main() {
flag.Parse()
fmt.Println("Server start on: ", port)
fmt.Println("Directory to serve: ", down)
fmt.Println("Directory to upload files: ", up)
http.HandleFunc("/upload", uploadHandler)
http.Handle("/", http.FileServer(http.Dir(down)))
err := http.ListenAndServe(":"+port, nil)
if err != nil {
fmt.Printf("Failed to start server, %v\n", err)
}
}
func uploadHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "POST":
err := r.ParseMultipartForm(32 << 20) // 32MB is the default size used by FormFile
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
m := r.MultipartForm
files := m.File["files"]
for i := range files {
file, err := files[i].Open()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
dst, err := os.Create(fmt.Sprintf("%s/%s", up, files[i].Filename))
defer dst.Close()
if _, err := io.Copy(dst, file); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
display(w, nil)
}
case "GET":
display(w, nil)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func display(w http.ResponseWriter, data interface{}) {
t, err := template.ParseFiles("upload.html")
if err != nil {
panic(fmt.Sprintf("An error ocurred when parsing template, %v\n", err))
}
t.Execute(w, nil)
}