client: add minimal client api for the http api
All checks were successful
continuous-integration/drone/push Build is passing
All checks were successful
continuous-integration/drone/push Build is passing
This commit is contained in:
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,2 +1,2 @@
|
|||||||
geoipapi
|
./geoipapi
|
||||||
*~
|
*~
|
77
client/geoipapi/geoipclient.go
Normal file
77
client/geoipapi/geoipclient.go
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
package geoipapi
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"fmt"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/netip"
|
||||||
|
"net/url"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/oschwald/geoip2-golang"
|
||||||
|
"go.opentelemetry.io/otel"
|
||||||
|
"go.opentelemetry.io/otel/attribute"
|
||||||
|
)
|
||||||
|
|
||||||
|
var client http.Client
|
||||||
|
|
||||||
|
func init() {
|
||||||
|
netTransport := &http.Transport{
|
||||||
|
Dial: (&net.Dialer{
|
||||||
|
Timeout: 5 * time.Second,
|
||||||
|
}).Dial,
|
||||||
|
TLSHandshakeTimeout: 5 * time.Second,
|
||||||
|
}
|
||||||
|
client = http.Client{
|
||||||
|
Timeout: time.Second * 10,
|
||||||
|
Transport: netTransport,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func GetCity(ctx context.Context, ip netip.Addr) (*geoip2.City, error) {
|
||||||
|
ctx, span := otel.Tracer("geoipapi").Start(ctx, "geoip.GetCity")
|
||||||
|
defer span.End()
|
||||||
|
|
||||||
|
baseURL := os.Getenv("geoip_service")
|
||||||
|
if len(baseURL) == 0 {
|
||||||
|
return nil, fmt.Errorf("geoip_service not configured")
|
||||||
|
}
|
||||||
|
|
||||||
|
q := url.Values{}
|
||||||
|
q.Set("ip", ip.String())
|
||||||
|
|
||||||
|
span.SetAttributes(attribute.String("ip", ip.String()))
|
||||||
|
|
||||||
|
reqURL, err := url.Parse(fmt.Sprintf("http://%s/api/json?%s", baseURL, q.Encode()))
|
||||||
|
if err != nil {
|
||||||
|
span.RecordError(err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
req, err := http.NewRequestWithContext(ctx, "GET", reqURL.String(), nil)
|
||||||
|
if err != nil {
|
||||||
|
span.RecordError(err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
resp, err := client.Do(req)
|
||||||
|
if err != nil {
|
||||||
|
span.RecordError(err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
dec := json.NewDecoder(resp.Body)
|
||||||
|
|
||||||
|
city := geoip2.City{}
|
||||||
|
err = dec.Decode(&city)
|
||||||
|
if err != nil {
|
||||||
|
span.RecordError(err)
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &city, nil
|
||||||
|
}
|
Reference in New Issue
Block a user