-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.go
214 lines (194 loc) · 5.87 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
// Copyright 2020 Shivam Rathore
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package freeGeoIP
import (
"context"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strconv"
"sync"
"time"
)
const (
Endpoint = "https://freegeoip.app/json/"
_HeaderResetIn = "x-ratelimit-reset"
_HeaderLimit = "x-ratelimit-limit"
_HeaderRemaining = "x-ratelimit-remaining"
)
var (
// globalMeta maintains the API meta information for the cached information
// and mu protects globalMeta against updates
mu *sync.Mutex
globalMeta = &MetaInfo{}
// noopLogger is the quiet logger to handle nil logger in Client
noopLogger = log.New(ioutil.Discard, "", 0)
// defaultLogger is the default logger implementation for DefaultClient
defaultLogger = log.New(os.Stderr, "freeGeoIP ", log.LstdFlags)
)
func init() {
mu = &sync.Mutex{}
mu.Lock()
globalMeta.Limit = 15000
globalMeta.Remaining = globalMeta.Limit
globalMeta.ResetIn = time.Hour
mu.Unlock()
}
// Client is our Free GeoLocation information client.
// If Cache is not provided then will always make the http request to https://freegeoip.app/json/
// If HttpCli is not provided then will always use http.DefaultClient
// And if Logger is not provided, then a noopLogger will be used
type Client struct {
Cache ICache
HttpCli *http.Client
Logger *log.Logger
}
// DefaultClient is the library default geo location client with an in-memory
// cache with a default expiry of 24 Hours and will set a total of 2 seconds
// timeout in http.Client, with the default inbuilt library logger.
func DefaultClient() *Client {
return &Client{
Cache: DefaultCache(),
HttpCli: &http.Client{Timeout: time.Second * 2},
Logger: defaultLogger,
}
}
// GetGeoInfoFromString will return the API response for provided `ip` string
// It call the GetGeoInfo.
func (c *Client) GetGeoInfoFromString(ctx context.Context, ip string) Response {
_ip := ParseIP(ip)
if len(_ip) == 0 && ip != "" {
return fillResponse(nil, ErrNoResponse, nil, struct{}{})
}
return c.GetGeoInfo(ctx, _ip)
}
// GetGeoInfo will return the free geolocation api response for the provided IP
// and uses the Cached response, if cache is used. For default empty Client
// behaviour see Client object description
func (c *Client) GetGeoInfo(ctx context.Context, ip IP) Response {
if c.Logger == nil {
c.Logger = noopLogger
}
if c.HttpCli == nil {
c.HttpCli = http.DefaultClient
}
if c.Cache == nil {
c.Cache = NoopCache{}
}
// check cache
info, err := c.Cache.Get(ctx, ip)
if err == nil {
c.Logger.Println("cache is hit for '" + ip.String())
return fillResponse(info, nil, nil, struct{}{})
}
c.Logger.Println("cache for '"+ip.String()+"' is missed with error:", err)
// call api
return c.do(ctx, ip)
}
// do is the internal method used to make the http request to API
func (c *Client) do(ctx context.Context, ip IP) Response {
// http request
u, _ := url.Parse(Endpoint)
u.Path += ip.String()
req, err := http.NewRequest(http.MethodGet, u.String(), nil)
if err != nil {
c.Logger.Println("http.NewRequest error:", err)
return fillResponse(nil, wrapError("http", err), nil)
}
// request's response
resp, err := c.HttpCli.Do(req.WithContext(ctx))
if err != nil {
c.Logger.Println("http response error:", err)
return fillResponse(nil, wrapError("http", err), nil)
}
defer resp.Body.Close()
// meta information
meta := extractMetaInfo(resp.Header)
// rate limit check
if resp.StatusCode == http.StatusForbidden {
c.Logger.Println(ErrLimitReached)
return fillResponse(nil, ErrLimitReached, meta)
}
// invalid ip
if resp.StatusCode == http.StatusNotFound {
c.Logger.Println(ErrNoResponse)
return fillResponse(nil, ErrNoResponse, meta)
}
// non ok status code
if resp.StatusCode != http.StatusOK {
data, _ := ioutil.ReadAll(resp.Body)
c.Logger.Println(ErrInternal, "status:", resp.Status, "response:", string(data))
return fillResponse(nil, ErrInternal, meta)
}
// finally response
data, err := ioutil.ReadAll(resp.Body)
if err != nil {
c.Logger.Println("unreadable response body:", err)
return fillResponse(nil, wrapError("response", err), meta)
}
// decode
info, err := Decoder(data)
if info != nil {
c.Cache.Set(ctx, info)
if len(ip) == 0 { // hack: to cache empty ip for next call
tmp := info.IP
info.IP = nil
c.Cache.Set(ctx, info)
info.IP = tmp
}
}
return fillResponse(info, err, meta)
}
// extractMetaInfo extract the meta details regarding the limit and reset timer
// from the API response headers
func extractMetaInfo(header http.Header) *MetaInfo {
atoi := func(key string) int64 {
v, _ := strconv.Atoi(header.Get(key))
return int64(v)
}
meta := &MetaInfo{
ResetIn: time.Second * time.Duration(atoi(_HeaderResetIn)),
Limit: atoi(_HeaderLimit),
Remaining: atoi(_HeaderRemaining),
}
mu.Lock()
globalMeta.Limit = meta.Limit
globalMeta.Remaining = meta.Remaining
globalMeta.ResetIn = meta.ResetIn
mu.Unlock()
return meta
}
// fillResponse returns a combined response for any client method call
func fillResponse(info *Info, err error, meta *MetaInfo, cached ...struct{}) Response {
if info != nil { // create a copy of info
tmp := *info
info = &tmp
}
res := Response{
Info: info,
Error: err,
Cached: len(cached) > 0,
Meta: meta,
}
if res.Meta == nil {
res.Meta = &MetaInfo{
ResetIn: globalMeta.ResetIn,
Limit: globalMeta.Limit,
Remaining: globalMeta.Remaining,
}
}
return res
}