-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfileUpload.go
75 lines (61 loc) · 1.45 KB
/
fileUpload.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 (
"io"
"net/http"
"encoding/json"
"os"
)
type Result struct {
Success bool
Message string
}
//This is where the action happens.
func uploadHandler(w http.ResponseWriter, r *http.Request) {
success := Result{true, "All good"}
switch r.Method {
//POST takes the uploaded file(s) and saves it to disk.
case "POST":
//get the multipart reader for the request.
reader, err := r.MultipartReader()
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.FileName() is empty, skip this iteration.
if part.FileName() == "" {
continue
}
dst, err := os.Create("/tmp/pdsEnv/" + part.FormName())
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.
js, err := json.Marshal(success)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
}
func main() {
http.HandleFunc("/funf_connector/set_funf_data", uploadHandler)
//Listen on port 8002
http.ListenAndServe(":8002", nil)
}