-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
285 lines (239 loc) · 7.42 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
package main
import (
"fmt"
"net/http"
"encoding/json"
"log"
"strconv"
"reflect"
elastic "gopkg.in/olivere/elastic.v3"
"github.com/pborman/uuid"
//"context"
//"cloud.google.com/go/bigtable"
// new libs
"github.com/auth0/go-jwt-middleware"
"github.com/dgrijalva/jwt-go"
"github.com/gorilla/mux"
"context"// open terminal, go get xxx
"cloud.google.com/go/storage" // open terminal, go get xxx
"io"
)
var mySigningKey = []byte("secret")
const (
INDEX = "around"
TYPE = "post"
DISTANCE = "200km"
// Needs to update
PROJECT_ID = "around-204403"
BT_INSTANCE = "around-post"
// Needs to update this URL if you deploy it to cloud.
ES_URL = "http://35.229.51.69:9200"
BUCKET_NAME = "post-images-204403"
)
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"`
}
func main() {
// Create a client
client, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetSniff(false))
if err != nil {
panic(err)
return
}
// Use the IndexExists service to check if a specified index exists.
exists, err := client.IndexExists(INDEX).Do()
if err != nil {
panic(err)
}
if !exists {
// Create a new index.
mapping := `{
"mappings":{
"post":{
"properties":{
"location":{
"type":"geo_point"
}
}
}
}
}
`
_, err := client.CreateIndex(INDEX).Body(mapping).Do()
if err != nil {
// Handle error
panic(err)
}
}
fmt.Println("started server")
r := mux.NewRouter()
var jwtMiddleware = jwtmiddleware.New(jwtmiddleware.Options{
ValidationKeyGetter: func(token *jwt.Token) (interface{}, error) {
return mySigningKey, nil
},
SigningMethod: jwt.SigningMethodHS256,
})
r.Handle("/post", jwtMiddleware.Handler(http.HandlerFunc(handlerPost))).Methods("POST")
r.Handle("/search", jwtMiddleware.Handler(http.HandlerFunc(handlerSearch))).Methods("GET")
r.Handle("/login", http.HandlerFunc(loginHandler)).Methods("POST")
r.Handle("/signup", http.HandlerFunc(signupHandler)).Methods("POST")
http.Handle("/", r)
log.Fatal(http.ListenAndServe(":8080", nil))
}
func handlerPost(w http.ResponseWriter, r *http.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")
// 32 << 20 is the maxMemory param for ParseMultipartForm, equals to 32MB (1MB = 1024 * 1024 bytes = 2^20 bytes)
// After you call ParseMultipartForm, the file will be saved in the server memory with maxMemory size.
// If the file size is larger than maxMemory, the rest of the data will be saved in a system temporary file.
r.ParseMultipartForm(32 << 20)
// Parse from form data.
fmt.Printf("Received one post request %s\n", r.FormValue("message"))
lat, _ := strconv.ParseFloat(r.FormValue("lat"), 64)
lon, _ := strconv.ParseFloat(r.FormValue("lon"), 64)
p := &Post{
User: "1111",
Message: r.FormValue("message"),
Location: Location{
Lat: lat,
Lon: lon,
},
}
id := uuid.New()
file, _, err := r.FormFile("image")
if err != nil {
http.Error(w, "Image is not available", http.StatusInternalServerError)
fmt.Printf("Image is not available %v.\n", err)
return
}
defer file.Close()
ctx := context.Background()
// replace it with your real bucket name.
_, attrs, err := saveToGCS(ctx, file, BUCKET_NAME, id)
if err != nil {
http.Error(w, "GCS is not setup", http.StatusInternalServerError)
fmt.Printf("GCS is not setup %v\n", err)
return
}
// Update the media link after saving to GCS.
p.Url = attrs.MediaLink
// Save to ES.
saveToES(p, id)
}
// Save a post to ElasticSearch
func saveToES(p *Post, id string) {
// Create a client
es_client, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetSniff(false))
if err != nil {
panic(err)
fmt.Println("connect to ES failed")
return
}
// Save it to index
_, err = es_client.Index().
Index(INDEX).
Type(TYPE).
Id(id).
BodyJson(p).
Refresh(true).
Do()
if err != nil {
panic(err)
return
}
fmt.Printf("Post is saved to Index: %s\n", p.Message)
}
// Save an image to GCS.
func saveToGCS(ctx context.Context, r io.Reader, bucket, name string) (*storage.ObjectHandle, *storage.ObjectAttrs, error) {
// create a client
client, err := storage.NewClient(ctx)
if err != nil {
return nil, nil, err
}
defer client.Close()
// create a bucket instance
bh := client.Bucket(bucket)
// Next check if the bucket exists
if _, err = bh.Attrs(ctx); err != nil {
return nil, nil, err
}
obj := bh.Object(name)
w := obj.NewWriter(ctx)
if _, err := io.Copy(w, r); err != nil {
return nil, nil, err
}
if err := w.Close(); err != nil {
return nil, nil, err
}
if err := obj.ACL().Set(ctx, storage.AllUsers, storage.RoleReader); err != nil {
return nil, nil, err
}
attrs, err := obj.Attrs(ctx)
fmt.Printf("Post is saved to GCS: %s\n", attrs.MediaLink)
return obj, attrs, err
}
func handlerSearch(w http.ResponseWriter, r *http.Request) {
fmt.Println("Received one request for search")
lat, _ := strconv.ParseFloat(r.URL.Query().Get("lat"), 64)
lon, _ := strconv.ParseFloat(r.URL.Query().Get("lon"), 64)
// range is option
ran := DISTANCE
if val := r.URL.Query().Get("range"); val != "" {
ran = val + "km"
}
fmt.Printf("Search received: %f %f %s\n", lat, lon, ran)
// Create a client
client, err := elastic.NewClient(elastic.SetURL(ES_URL), elastic.SetSniff(false))
if err != nil {
panic(err)
return
}
// Define geo distance query as specified in
// https://www.elastic.co/guide/en/elasticsearch/reference/5.2/query-dsl-geo-distance-query.html
q := elastic.NewGeoDistanceQuery("location")
q = q.Distance(ran).Lat(lat).Lon(lon)
// Some delay may range from seconds to minutes. So if you don't get enough results. Try it later.
searchResult, err := client.Search().
Index(INDEX).
Query(q).
Pretty(true).
Do()
if err != nil {
// Handle error
panic(err)
}
// searchResult is of type SearchResult and returns hits, suggestions,
// and all kinds of other information from Elasticsearch.
fmt.Printf("Query took %d milliseconds\n", searchResult.TookInMillis)
// TotalHits is another convenience function that works even when something goes wrong.
fmt.Printf("Found a total of %d post\n", searchResult.TotalHits())
// Each is a convenience function that iterates over hits in a search result.
// It makes sure you don't need to check for nil values in the response.
// However, it ignores errors in serialization.
var typ Post
var ps []Post
for _, item := range searchResult.Each(reflect.TypeOf(typ)) {
// instance of
p := item.(Post) // p = (Post) item
fmt.Printf("Post by %s: %s at lat %v and lon %v\n", p.User, p.Message, p.Location.Lat, p.Location.Lon)
// TODO(student homework): Perform filtering based on keywords such as web spam etc.
ps = append(ps, p)
}
js, err := json.Marshal(ps)
if err != nil {
panic(err)
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Write(js)
}