/
api.go
85 lines (72 loc) · 1.95 KB
/
api.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
package api
import (
"encoding/json"
"io"
"log/slog"
"net/http"
"os"
"strconv"
"time"
"github.com/jvanrhyn/brgeo/model"
)
// GetGeoInfo accepts an IP Address to perform a lookup
// of the geolocation information of the IP Address
// form KeyCDNs' Geo service.
// This service is rate limited to a maximum of 3 calls per second.
func GetGeoInfo(ipaddress string) (model.GeoData, int) {
client := &http.Client{}
path := os.Getenv("SERVICE_URL") + "?host=" + ipaddress
req, err := http.NewRequest("GET", path, nil)
if err != nil {
panic(err)
}
// Setting the User-Agent header
req.Header.Set("User-Agent", os.Getenv("USER_AGENT"))
// Define a re-usable response object needed to
// the retry pattern implemented
var resp *http.Response
// Setup for a backoff retry pattern
maxRetries, _ := strconv.Atoi(os.Getenv("MAX_RETRIES"))
if maxRetries < 3 {
maxRetries = 3
}
slog.Info("Max retries", "retries", maxRetries)
baseInterval := 500 * time.Millisecond
retryFactor := 2.0
retry := 0
for i := 0; i < maxRetries; i++ {
slog.Info("Attempts Counter", "attempt", i)
resp, err = client.Do(req)
if err == nil && resp.StatusCode == http.StatusOK {
err := resp.Body.Close()
if err != nil {
return model.GeoData{}, 0
}
break
}
// If this wasn't the last attempt, sleep for a while before retrying
if i < maxRetries-1 {
sleepDuration := time.Duration(float64(baseInterval) * float64(i+1) * retryFactor)
retry = i
slog.Info("Sleeping on error", "duration", sleepDuration, "error", err)
time.Sleep(sleepDuration)
continue
} else {
// If this was the last attempt, handle the error (e.g., by panicking)
panic(err)
}
}
if resp != nil {
body, err := io.ReadAll(resp.Body)
if err != nil {
slog.Error(err.Error())
}
var geoResponse model.Response
err = json.Unmarshal(body, &geoResponse)
if err != nil {
slog.Error(err.Error())
}
return geoResponse.Data.Geo, retry
}
return model.GeoData{}, 0
}