-
Notifications
You must be signed in to change notification settings - Fork 1
/
ipinfo.go
106 lines (87 loc) · 2.58 KB
/
ipinfo.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
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"go.opentelemetry.io/otel/codes"
"go.opentelemetry.io/otel/trace"
)
type IPInfoIo struct {
IP string `json:"ip"`
Hostname string `json:"hostname"`
City string `json:"city"`
Region string `json:"region"`
Country string `json:"country"`
Loc string `json:"loc"`
Org string `json:"org"`
Postal string `json:"postal"`
Timezone string `json:"timezone"`
Latitude float64 `json:"latitute"`
Longitude float64 `json:"longitude"`
}
func getIpInfoIo(host string, ctx context.Context, tracer trace.Tracer) (IPInfoIo, error) {
childCtx, span := tracer.Start(
ctx,
"getIpInfoIo")
defer span.End()
log.Printf("Getting IP info for '%s' from ipinfo.io", host)
url := fmt.Sprintf("https://ipinfo.io/%s", host)
req, err := http.NewRequest("GET", url, nil)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return IPInfoIo{}, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", ipinfoIoToken))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return IPInfoIo{}, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return IPInfoIo{}, err
}
result, err := unmarshallgetIpInfoIo(body, childCtx, tracer)
if err != nil {
span.RecordError(err)
span.SetStatus(codes.Error, err.Error())
return IPInfoIo{}, err
}
span.AddEvent("Successfully got IP info from ipinfo.io")
span.SetStatus(codes.Ok, fmt.Sprintf("Successfully got IP info for '%s' from ipinfo.io", host))
return result, nil
}
func parseLoc(loc string, ctx context.Context, tracer trace.Tracer) (float64, float64) {
_, span := tracer.Start(
ctx,
"parseLoc")
defer span.End()
var lat, long float64
fmt.Sscanf(loc, "%f,%f", &lat, &long)
span.AddEvent("Successfully parsed location")
span.SetStatus(codes.Ok, "Successfully parsed location")
return lat, long
}
func unmarshallgetIpInfoIo(body []byte, ctx context.Context, tracer trace.Tracer) (IPInfoIo, error) {
childCtx, span := tracer.Start(
ctx,
"unmarshallgetIpInfoIo")
defer span.End()
var ipInfoIo IPInfoIo
json.Unmarshal(body, &ipInfoIo)
lat, long := parseLoc(ipInfoIo.Loc, childCtx, tracer)
ipInfoIo.Latitude = lat
ipInfoIo.Longitude = long
span.AddEvent("Successfully unmarshalled IP info from ipinfo.io")
span.SetStatus(codes.Ok, "Successfully unmarshalled IP info from ipinfo.io")
return ipInfoIo, nil
}