-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.go
More file actions
251 lines (202 loc) · 5.37 KB
/
Copy pathserver.go
File metadata and controls
251 lines (202 loc) · 5.37 KB
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
package main
import (
"encoding/json"
"errors"
"io/ioutil"
"log"
"net"
"net/http"
"os"
"strconv"
"time"
"github.com/gorilla/mux"
)
const (
urlUploadID = "upload_id"
urlChunkID = "chunk_id"
formValueChunk = "chunk"
longPollTimeout = 2 * time.Minute
)
var (
errUploadNotFound = errors.New("upload not found")
errBadRequest = errors.New("bad request")
errAlreadyUploading = errors.New("already uploading")
)
func main() {
port := os.Getenv("PORT")
if len(port) == 0 {
port = "8080"
}
mux := mux.NewRouter()
gets := mux.Methods("GET").PathPrefix("/api").Subrouter()
posts := mux.Methods("POST").PathPrefix("/api").Subrouter()
gets.Handle("/upload/{upload_id}/status", handleErr(statusHandler))
finishedHandler, processedHandler := longPoll(finishedSelector), longPoll(processedSelector)
gets.Handle("/upload/{upload_id}/finished", handleErr(finishedHandler.ServeHTTP))
gets.Handle("/upload/{upload_id}/processed", handleErr(processedHandler.ServeHTTP))
posts.Handle("upload/{upload_id}/chunk/{chunk_id}", handleErr(chunkHandler))
posts.Handle("upload", handleErr(uploadHandler))
log.Println(http.ListenAndServe(net.JoinHostPort("", port), mux))
}
type UploadRequest struct {
Name string `json:"name"`
Size int64 `json:"size,omitempty"`
Chunks int `json:"chunks,omitempty"`
ChunkSize int `json:"chunk_size,omitempty"`
}
// String returns a "unique" identifier for this UploadRequest.
func (u UploadRequest) String() string {
return u.Name + strconv.FormatInt(u.Size, 10) + strconv.Itoa(u.Chunks) + strconv.Itoa(u.ChunkSize)
}
type UploadResponse struct {
ID uint `json:"upload_id,omitempty"`
Status string `json:"status"`
Error string `json:"error,omitempty"`
File *File `json:"file,omitempty"`
}
type File struct {
Name string `json:"name,omitempty"`
Size int64 `json:"size,omitempty"`
Author string `json:"author,omitempty"`
Date time.Time `json:"date,omitempty"`
Thumbnail string `json:"thumbnail,omitempty"`
}
type StatusResponse struct {
Status []int `json:"status"`
}
func getUploadID(r *http.Request) (uint, error) {
vals := mux.Vars(r)
str, ok := vals[urlUploadID]
if !ok {
return 0, errBadRequest
}
bigID, err := strconv.ParseUint(str, 10, 32)
if err != nil {
return 0, errBadRequest
}
return uint(bigID), nil
}
func getUpload(r *http.Request) (upload *Upload, err error) {
var id uint
id, err = getUploadID(r)
if err != nil {
return nil, err
}
uploadMut.RLock()
upload, ok := uploads[id]
uploadMut.RUnlock()
if !ok {
return nil, errUploadNotFound
}
return upload, nil
}
func uploadHandler(w http.ResponseWriter, r *http.Request) (err error) {
dec := json.NewDecoder(r.Body)
// Decode json request
var req UploadRequest
if err = dec.Decode(&req); err != nil {
return err
}
if err = r.Body.Close(); err != nil {
return err
}
// TODO(dylanj): Check if we have the file in DB, because currently this constant won't do
haveFile := false
// Prepare response
var resp UploadResponse
if haveFile {
resp.Status = "error"
resp.Error = "file already exists"
// TODO(dylanj): Fill out the files stuff from the DB
resp.File = &File{
Name: "lollerskates.jpepng",
Size: 18348,
Author: "fish",
Date: time.Now(),
Thumbnail: "/thumb.jpegif",
}
} else {
resp.Status = "success"
resp.ID, err = createSlot(req)
if err != nil {
return err
}
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
return enc.Encode(&resp)
}
func statusHandler(w http.ResponseWriter, r *http.Request) (err error) {
upload, err := getUpload(r)
if err != nil {
return err
}
var status StatusResponse
statusChan, ok := <-upload.Status
if ok {
status.Status = <-statusChan
}
w.Header().Set("Content-Type", "application/json")
enc := json.NewEncoder(w)
return enc.Encode(&status)
}
func chunkHandler(w http.ResponseWriter, r *http.Request) (err error) {
vars := mux.Vars(r)
chunkID, err := strconv.Atoi(vars[urlChunkID])
if err != nil {
return err
}
file, _, err := r.FormFile(formValueChunk)
if err != nil {
return err
}
defer file.Close()
upload, err := getUpload(r)
if err != nil {
return err
}
_, ok := <-upload.WriteStart
if !ok {
w.WriteHeader(http.StatusNotFound) // Upload was timeouted before we could write
return nil
}
offset := int64(chunkID) * int64(upload.FileInfo.ChunkSize)
data, err := ioutil.ReadAll(file)
if err != nil {
upload.WriteEnd <- -1
return err
}
_, err = upload.File.WriteAt(data, offset)
if err != nil {
upload.WriteEnd <- -1
return err
}
upload.WriteEnd <- chunkID
return nil
}
type longPoll func(u *Upload) chan bool
func (selector longPoll) ServeHTTP(w http.ResponseWriter, r *http.Request) error {
upload, err := getUpload(r)
if err != nil {
return err
}
select {
case <-time.After(longPollTimeout):
w.WriteHeader(http.StatusRequestTimeout)
return nil
case <-selector(upload):
}
var resp File
resp.Name = "My file"
// TODO(dylanj): Pull file from DB and fill with love, if it has thumbnail it has it, if not it doesn't
// but if the URL hit was api/upload/{id}/processed then it will have a thumbnail if it was ever going
// to get one.
enc := json.NewEncoder(w)
return enc.Encode(&resp)
}
func finishedSelector(u *Upload) chan bool {
return u.FinishLatch
}
func processedSelector(u *Upload) chan bool {
return u.PostProcessLatch
}