-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_cafe.go
104 lines (87 loc) · 2.41 KB
/
handler_cafe.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
package main
import (
"fmt"
"log"
"net/http"
"strconv"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
"github.com/kiambogo/coffeeworks/models"
"github.com/kiambogo/coffeeworks/support"
"googlemaps.github.io/maps"
)
// GetCafe queries for a particular cafe by id
func GetCafe(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r)
cafeID, ok := vars["id"]
if !ok {
support.ReturnString(w, 400, "Cafe ID required")
}
cafe, err := PlacesClient.GetPlaceDetails(cafeID)
if err != nil {
support.PrintError(err)
support.ReturnString(w, 500, "Something went wrong, yo")
return
}
// Add the score for the cafe, if exists
score := &models.Score{}
if err := score.LoadLatest(cafe.PlaceID, models.DB); err != nil {
if !gorm.IsRecordNotFoundError(err) {
support.LogError(err, "GetCafe (%v) - retrieving score", cafeID)
support.ReturnString(w, 500, "Something went wrong, yo")
return
}
} else {
cafe.Score = score
}
support.ReturnPrettyJSON(w, 200, cafe)
}
// ListCafes queries for cafes around a certain point
func ListCafes(w http.ResponseWriter, r *http.Request) {
latLng, err := parseLatLng(r)
if err != nil {
support.ReturnString(w, 400, "Need numeric query params 'lat' and 'lng'")
return
}
radiusStr := support.GetQueryParamDefault(r, "radius", "100")
radius, err := strconv.Atoi(radiusStr)
if err != nil {
support.ReturnString(w, 400, "Radius, when specified, must be of numeric type")
return
}
places, err := PlacesClient.FindPlacesNearArea(latLng, radius)
if err != nil {
support.PrintError(err)
support.ReturnString(w, 500, "Something went wrong, yo")
return
}
support.ReturnPrettyJSON(w, 200, places)
}
func parseLatLng(r *http.Request) (maps.LatLng, error) {
var lat, lng float64
var err error
var latLng maps.LatLng
latParams := support.GetQueryParam(r, "lat")
lngParams := support.GetQueryParam(r, "lng")
if len(latParams) == 0 || len(lngParams) == 0 {
return latLng, fmt.Errorf("'lat' or 'lng' query params were not present")
}
errors := []error{}
lat, err = strconv.ParseFloat(latParams[0], 64)
if err != nil {
errors = append(errors, err)
}
lng, err = strconv.ParseFloat(lngParams[0], 64)
if err != nil {
errors = append(errors, err)
}
if len(errors) > 0 {
log.Printf("%v", errors)
return latLng, fmt.Errorf("'lat' or 'lng' query params were not numeric types")
}
latLng = maps.LatLng{
Lat: lat,
Lng: lng,
}
return latLng, nil
}