-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathimageup.go
178 lines (149 loc) · 4.15 KB
/
imageup.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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strings"
"cloud.google.com/go/storage"
)
type jsonResp struct {
Code int `json:"code"`
Message string `json:"message"`
}
// ImageConfig represents both the input and output for a file.
type ImageConfig struct {
FileName string `json:"fileName"`
Name string `json:"name"`
URL string `json:"url"`
Fill bool `json:"fill"`
Width int `json:"width"`
Height int `json:"height"`
}
// AppConfig for the global singleton
type AppConfig struct {
bh *storage.BucketHandle
}
// App is the singleton.
var App = &AppConfig{}
// Grab a storage bucket client instance. This will persist throughout the
// lifetime of the server.
func configureStorage(bucketID string) (*storage.BucketHandle, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return nil, err
}
return client.Bucket(bucketID), nil
}
// GetEnv grabs env with a fallback
func GetEnv(key, fallback string) string {
if value, ok := os.LookupEnv(key); ok {
return value
}
return fallback
}
// Provision the response for a json payload.
func jsonResponse(w http.ResponseWriter, code int, data interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
json.NewEncoder(w).Encode(data)
}
// Remove all files in array. This is used to clean up something that went
// wrong.
func removeAll(files []ImageConfig) {
for _, conf := range files {
go RemoveFileFromGCP(conf.FileName)
}
}
// UploadFile uploads a file to the server
func handleRequest(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", GetEnv("CORS", "*"))
switch r.Method {
case http.MethodDelete:
for _, fname := range strings.Split(r.FormValue("files"), ",") {
go RemoveFileFromGCP(strings.TrimSpace(fname))
}
jsonResponse(w, http.StatusOK, jsonResp{
http.StatusOK,
"file(s) queued to be removed",
})
case http.MethodPost:
// Grab the file from the request.
file, handle, err := r.FormFile("file")
if err != nil {
Error("Error retrieving file: %v", err)
jsonResponse(w, http.StatusBadRequest, jsonResp{
http.StatusBadRequest,
"problem finding the file",
})
return
}
defer file.Close()
// Parse the file configuration json array.
var configs []ImageConfig
if json.Unmarshal([]byte(r.FormValue("sizes")), &configs) != nil {
Error("Error handling params: %v", err)
Error("This is what the config looks like: %v", r.FormValue("sizes"))
jsonResponse(w, http.StatusNotAcceptable, jsonResp{
http.StatusBadRequest,
"there is a problem with the size configuration",
})
return
}
if len(configs) < 1 {
Error("No size sent with request.")
jsonResponse(w, http.StatusNotAcceptable, jsonResp{
http.StatusBadRequest,
"there were no size instructions sent with request",
})
return
}
var uploadedFiles []ImageConfig
// Handle the file uploads.
for _, conf := range configs {
Info("Processing image with size: %v", conf)
if _, err = file.Seek(0, os.SEEK_SET); err != nil {
Error("Error seeking file: %v", err)
removeAll(uploadedFiles)
jsonResponse(w, http.StatusBadRequest, jsonResp{
http.StatusBadRequest,
"error seeking file",
})
return
}
c, err := UploadFile(conf, handle)
if err != nil {
Error("Error uploading file: %v", err)
removeAll(uploadedFiles)
jsonResponse(w, http.StatusBadRequest, jsonResp{
http.StatusBadRequest,
"unknown error while uploading",
})
return
}
uploadedFiles = append(uploadedFiles, *c)
}
jsonResponse(w, http.StatusCreated, uploadedFiles)
default:
Error("Error with the request (non-POST or non-DELETE)")
jsonResponse(w, http.StatusMethodNotAllowed, jsonResp{
http.StatusMethodNotAllowed,
"fail",
})
}
}
func main() {
port := GetEnv("SERVER_PORT", "31111")
bucket := GetEnv("BUCKET_ID", "default")
bh, err := configureStorage(bucket)
if err != nil {
log.Fatal(err)
}
Info("Listening on port %s. Using bucket %s.", port, bucket)
App.bh = bh
http.HandleFunc("/", handleRequest)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", port), nil))
}