forked from skyline-ai/spotcrime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
116 lines (92 loc) · 2.28 KB
/
api.go
File metadata and controls
116 lines (92 loc) · 2.28 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
package spotcrime
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
)
const (
userAgent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36"
baseURL = "http://api.spotcrime.com/crimes.json"
// in case no radius is provided (only lat,lon), use this as the default radius
defaultRadius = 0.01
)
// Client is the Spotcrime client. It contains all the different resources available.
type Client struct {
key string
Debug bool
}
// New creates a new Spotcrime client with the appropriate secret key
func New(key string) (*Client, error) {
if len(key) == 0 {
return nil, fmt.Errorf("must provide key")
}
return &Client{
key: key,
}, nil
}
// Request contains information to sent to the api endpoint
type Request struct {
Lat float64
Lon float64
Radius float64
Proxy string
}
// Response contains Results from the API request
type Response struct {
Results Results `json:"crimes"`
}
// Results is a slice of Result
type Results []Result
// Result directly corresponds to the JSON returned by the API
type Result struct {
CDID int `json:"cdid"`
Type string `json:"type"`
Date string `json:"date"`
Link string `json:"link"`
Lat float64 `json:"lat"`
Lon float64 `json:"lon"`
}
// GetCrimes fetches crimes from Spotcrime API
func (c *Client) GetCrimes(r *Request) (*Response, error) {
if r.Lat == 0 || r.Lon == 0 {
return nil, fmt.Errorf("spotcrime.GetCrimes: must provide lat and lon")
}
if r.Radius == 0 {
r.Radius = defaultRadius
}
sURL := fmt.Sprintf("%s?key=%s&lat=%f&lon=%f&radius=%f", baseURL, c.key, r.Lat, r.Lon, r.Radius)
if c.Debug {
log.Printf("spotcrime.GetCrimes.sURL: %s", sURL)
}
client := &http.Client{}
if len(r.Proxy) > 0 {
_, err := url.Parse(r.Proxy)
if err == nil {
os.Setenv("HTTP_PROXY", r.Proxy)
}
}
req, err := http.NewRequest("GET", sURL, nil)
if err != nil {
log.Fatalln(err)
}
req.Header.Set("User-Agent", userAgent)
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
}
data, err := ioutil.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return nil, err
}
var response *Response
err = json.Unmarshal(data, &response)
if err != nil {
return nil, err
}
return response, nil
}