This repository was archived by the owner on Nov 30, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
208 lines (194 loc) · 6.13 KB
/
server.go
File metadata and controls
208 lines (194 loc) · 6.13 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
package api
import (
"encoding/json"
"io"
"log"
"net/http"
"strings"
"time"
"github.com/gorilla/mux"
)
const (
DefaultTokenURI = "https://accounts.google.com/o/oauth2/token"
DefaultListenAddr = ":8080"
AuthHeader = "Gifs-Username"
)
type Handler func(w http.ResponseWriter, r *http.Request, c Context)
func GetDomainMuxer(c Context) *mux.Router {
r := mux.NewRouter()
domainSuffix := c.RootDomain
if domainSuffix[0] == '.' {
domainSuffix = domainSuffix[1:]
}
r.HandleFunc("/", timeHandler(wrap(c, authWrapper(UploadHandler)))).Methods("POST").Host("{collection}." + domainSuffix)
r.HandleFunc("/", timeHandler(wrap(c, authWrapper(CreateCollection)))).Methods("POST").Host(domainSuffix)
r.Handle("/", timeHandler(wrap(c, CollectionList))).Methods("GET").Host("{collection}." + domainSuffix)
r.Handle("/{id}", timeHandler(wrap(c, GetBlob))).Methods("GET").Host("{collection}." + domainSuffix)
return r
}
func GetPathMuxer(c Context) *mux.Router {
r := mux.NewRouter()
r.HandleFunc("/", timeHandler(wrap(c, authWrapper(CreateCollection)))).Methods("POST")
r.HandleFunc("/{collection}", timeHandler(wrap(c, UploadHandler))).Methods("POST")
r.Handle("/{collection}", timeHandler(wrap(c, CollectionList))).Methods("GET")
r.Handle("/{collection}/{id}", timeHandler(wrap(c, GetBlob))).Methods("GET")
return r
}
func authWrapper(f Handler) Handler {
return func(w http.ResponseWriter, r *http.Request, c Context) {
r.Header.Del(AuthHeader)
bearer := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
if bearer == "" {
return
}
if c.Authorizer == nil {
return
}
user, err := c.Authorizer.Authorize(bearer, c)
if err != nil && err != InvalidBearerToken {
log.Println("Error authorizing request: " + err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
} else if err == InvalidBearerToken {
http.Error(w, "Invalid authorization", http.StatusUnauthorized)
return
}
r.Header.Set(AuthHeader, user)
f(w, r, c)
}
}
func wrap(c Context, f func(w http.ResponseWriter, r *http.Request, c Context)) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Println("Request received.")
f(w, r, c)
})
}
func timer(tag string, start time.Time) {
elapsed := time.Since(start)
log.Printf("%s took %s\n", tag, elapsed)
}
func timeHandler(f http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer timer("[timeHandler] "+r.Method+" request to "+r.URL.Path, time.Now())
f(w, r)
})
}
func UploadHandler(w http.ResponseWriter, r *http.Request, c Context) {
user := r.Header.Get(AuthHeader)
if user == "" {
http.Error(w, "Must be logged in", http.StatusUnauthorized)
return
}
vars := mux.Vars(r)
collection := vars["collection"]
if collection == "" {
http.Error(w, "collection doesn't exist", http.StatusNotFound)
return
}
reader, err := r.MultipartReader()
if err != nil {
log.Println("Error creating multipart reader: " + err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
ids := []string{}
for {
part, err := reader.NextPart()
if err != nil {
if err == io.EOF {
err = nil
break
}
log.Println("Error looping through reader parts: " + err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
name := part.FileName()
id, err := Upload(user, collection, name, part, c)
if err != nil {
log.Println("Error uploading file: " + err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
ids = append(ids, id)
}
encoder := json.NewEncoder(w)
err = encoder.Encode(ids)
if err != nil {
log.Println("Error encoding response: " + err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
}
}
func CollectionList(w http.ResponseWriter, r *http.Request, c Context) {
vars := mux.Vars(r)
collectionSlug := vars["collection"]
if collectionSlug == "" {
http.Error(w, "collection doesn't exist", http.StatusNotFound)
return
}
collection, err := c.Datastore.GetCollectionItems(collectionSlug)
if err != nil {
if err == CollectionNotFoundError {
http.Error(w, "collection doesn't exist", http.StatusNotFound)
return
}
log.Println("Error retrieving collection items: " + err.Error())
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
encoder := json.NewEncoder(w)
err = encoder.Encode(collection)
if err != nil {
log.Println("Error encoding response: " + err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func GetBlob(w http.ResponseWriter, r *http.Request, c Context) {
vars := mux.Vars(r)
collection := vars["collection"]
if collection == "" {
http.Error(w, "collection doesn't exist", http.StatusNotFound)
return
}
id := vars["id"]
if id == "" {
http.Error(w, "id doesn't exist", http.StatusNotFound)
return
}
item, err := c.Datastore.GetItemFromCollection(collection, id)
if err != nil {
log.Println("Error getting item: " + err.Error())
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
_, err = c.Storage.Download(item.Bucket, item.Blob, w, c)
if err != nil {
log.Println("Error downloading from GCS: " + err.Error())
http.Error(w, "internal server error", http.StatusInternalServerError)
return
}
}
func CreateCollection(w http.ResponseWriter, r *http.Request, c Context) {
var collection Collection
decoder := json.NewDecoder(r.Body)
err := decoder.Decode(&collection)
if err != nil {
log.Println("Error decoding request: " + err.Error())
http.Error(w, "Invalid request format", http.StatusBadRequest)
return
}
collection, err = c.Datastore.CreateCollection(collection.Slug, collection.Name)
if err != nil {
log.Println("Error creating collection: " + err.Error())
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
encoder := json.NewEncoder(w)
err = encoder.Encode(collection)
if err != nil {
log.Println("Error encoding response: " + err.Error())
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}