-
Notifications
You must be signed in to change notification settings - Fork 0
/
upload.go
73 lines (55 loc) · 1.25 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
package main
import (
"encoding/json"
"io"
"log"
"net/http"
"os"
"github.com/gorilla/mux"
)
// FileUploadStatus holds the status of the file upload function
type FileUploadStatus struct {
Response string `json:"response"`
Filename string `json:"filename"`
}
func imgUpload(w http.ResponseWriter, r *http.Request) {
var data FileUploadStatus
var filepath string
data.Response = "ok"
imgDir, ok := os.LookupEnv("IMG_FOLDER")
if ok != true {
log.Fatal("Image directory could not be read - Please set ENV Variables.")
http.Error(w, "Internal error", http.StatusInternalServerError)
return
}
fileURL := mux.Vars(r)["imgURL"]
data.Filename, filepath = generateFilename(imgDir)
err := downloadFile(filepath, fileURL)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
log.Panic(err)
return
}
imgUploaded.Inc()
json.NewEncoder(w).Encode(data)
}
func downloadFile(filepath string, url string) error {
// Get the data
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
// Create the file
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
// Write the body to file
_, err = io.Copy(out, resp.Body)
if err != nil {
return err
}
return nil
}