-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
299 lines (248 loc) · 7.16 KB
/
main.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
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"path/filepath"
"reflect"
"strconv"
"cloud.google.com/go/storage"
jwtmiddleware "github.com/auth0/go-jwt-middleware"
jwt "github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"github.com/olivere/elastic"
"github.com/pborman/uuid"
)
const (
POST_INDEX = "post"
DISTANCE = "200km"
ES_URL = "http://10.128.0.2:9200"
BUCKET_NAME = "kaikang-bucket"
)
var (
mediaTypes = map[string]string{
".jpeg": "image",
".jpg": "image",
".gif": "image",
".png": "image",
".mov": "video",
".mp4": "video",
".avi": "video",
".flv": "video",
".wmv": "video",
}
)
type Location struct {
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
type Post struct {
// `json:"user"` is for the json parsing of this User field. Otherwise, by default it's 'User'.
User string `json:"user"`
Message string `json:"message"`
Location Location `json:"location"`
Url string `json:"url"`
Type string `json:"type"`
Face float32 `json:"face"`
}
func main() {
fmt.Println("started-service")
jwtMiddleware := jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return []byte(mySigningKey), nil
},
SigningMethod: jwt.SigningMethodHS256,
})
r := mux.NewRouter()
r.Handle("/post", jwtMiddleware.Handler(http.HandlerFunc(handlerPost))).Methods("POST", "OPTIONS")
r.Handle("/search", jwtMiddleware.Handler(http.HandlerFunc(handlerSearch))).Methods("GET", "OPTIONS")
r.Handle("/cluster", jwtMiddleware.Handler(http.HandlerFunc(handlerCluster))).Methods("GET", "OPTIONS")
r.Handle("/signup", http.HandlerFunc(handlerSignup)).Methods("POST", "OPTIONS")
r.Handle("/login", http.HandlerFunc(handlerLogin)).Methods("POST", "OPTIONS")
log.Fatal(http.ListenAndServe(":8080", r))
}
func handlerPost(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one post request")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
if r.Method == "OPTIONS" {
return
}
user := r.Context().Value("user")
claims := user.(*jwt.Token).Claims
username := claims.(jwt.MapClaims)["username"]
lat, _ := strconv.ParseFloat(r.FormValue("lat"), 64)
lon, _ := strconv.ParseFloat(r.FormValue("lon"), 64)
p := &Post{
User: username.(string),
Message: r.FormValue("message"),
Location: Location{
Lat: lat,
Lon: lon,
},
}
file, header, err := r.FormFile("image")
if err != nil {
http.Error(w, "Image is not available", http.StatusBadRequest)
fmt.Printf("Image is not available %v\n", err)
return
}
suffix := filepath.Ext(header.Filename)
if t, ok := mediaTypes[suffix]; ok {
p.Type = t
} else {
p.Type = "unknown"
}
id := uuid.New()
mediaLink, err := saveToGCS(file, id)
if err != nil {
http.Error(w, "Failed to save image to GCS", http.StatusInternalServerError)
fmt.Printf("Failed to save image to GCS %v\n", err)
return
}
p.Url = mediaLink
if p.Type == "image" {
uri := fmt.Sprintf("gs://%s/%s", BUCKET_NAME, id)
if score, err := annotate(uri); err != nil {
http.Error(w, "Failed to annotate image", http.StatusInternalServerError)
fmt.Printf("Failed to annotate the image %v\n", err)
return
} else {
p.Face = score
}
}
err = saveToES(p, POST_INDEX, id)
if err != nil {
http.Error(w, "Failed to save post to Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to save post to Elasticsearch %v\n", err)
return
}
}
func handlerSearch(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one request for search")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
if r.Method == "OPTIONS" {
return
}
lat, _ := strconv.ParseFloat(r.URL.Query().Get("lat"), 64)
lon, _ := strconv.ParseFloat(r.URL.Query().Get("lon"), 64)
// range is optional
ran := DISTANCE
if val := r.URL.Query().Get("range"); val != "" {
ran = val + "km"
}
fmt.Println("range is ", ran)
query := elastic.NewGeoDistanceQuery("location")
query = query.Distance(ran).Lat(lat).Lon(lon)
searchResult, err := readFromES(query, POST_INDEX)
if err != nil {
http.Error(w, "Failed to read post from Elasticsearch", http.StatusInternalServerError)
fmt.Printf("Failed to read post from Elasticsearch %v.\n", err)
return
}
posts := getPostFromSearchResult(searchResult)
js, err := json.Marshal(posts)
if err != nil {
http.Error(w, "Failed to parse posts into JSON format", http.StatusInternalServerError)
fmt.Printf("Failed to parse posts into JSON format %v.\n", err)
return
}
w.Write(js)
}
func handlerCluster(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one cluster request")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type,Authorization")
if r.Method == "OPTIONS" {
return
}
term := r.URL.Query().Get("term")
query := elastic.NewRangeQuery(term).Gte(0.9)
searchResult, err := readFromES(query, POST_INDEX)
if err != nil {
http.Error(w, "Failed to read from Elasticsearch", http.StatusInternalServerError)
return
}
posts := getPostFromSearchResult(searchResult)
js, err := json.Marshal(posts)
if err != nil {
http.Error(w, "Failed to parse post object", http.StatusInternalServerError)
fmt.Printf("Failed to parse post object %v\n", err)
return
}
w.Write(js)
}
func readFromES(query elastic.Query, index string) (*elastic.SearchResult, error) {
client, err := elastic.NewClient(elastic.SetURL(ES_URL))
if err != nil {
return nil, err
}
searchResult, err := client.Search().
Index(index).
Query(query).
Pretty(true).
Do(context.Background())
if err != nil {
return nil, err
}
return searchResult, nil
}
func getPostFromSearchResult(searchResult *elastic.SearchResult) []Post {
var ptype Post
var posts []Post
for _, item := range searchResult.Each(reflect.TypeOf(ptype)) {
p := item.(Post)
posts = append(posts, p)
}
return posts
}
func saveToGCS(r io.Reader, objectName string) (string, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return "", err
}
bucket := client.Bucket(BUCKET_NAME)
if _, err := bucket.Attrs(ctx); err != nil {
return "", err
}
object := bucket.Object(objectName)
wc := object.NewWriter(ctx)
if _, err := io.Copy(wc, r); err != nil {
return "", err
}
if err := wc.Close(); err != nil {
return "", err
}
if err := object.ACL().Set(ctx, storage.AllUsers, storage.RoleReader); err != nil {
return "", err
}
attrs, err := object.Attrs(ctx)
if err != nil {
return "", err
}
fmt.Printf("Image is saved to GCS: %s\n", attrs.MediaLink)
return attrs.MediaLink, nil
}
func saveToES(i interface{}, index string, id string) error {
client, err := elastic.NewClient(elastic.SetURL(ES_URL))
if err != nil {
return err
}
_, err = client.Index().
Index(index).
Id(id).
BodyJson(i).
Do(context.Background())
if err != nil {
return err
}
return nil
}