Feature: log out country, region and city of IP

This commit is contained in:
Quentin McGaw
2021-02-08 00:01:14 +00:00
parent 3e527fee8b
commit 3deb65b529
6 changed files with 80 additions and 47 deletions

View File

@@ -2,16 +2,8 @@ package updater
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"net"
"net/http"
"sort"
"strings"
"github.com/qdm12/golibs/network"
)
func uniqueSortedIPs(ips []net.IP) []net.IP {
@@ -33,35 +25,3 @@ func uniqueSortedIPs(ips []net.IP) []net.IP {
})
return ips
}
var errBadHTTPStatus = errors.New("bad HTTP status received")
type ipInfoData struct {
Region string `json:"region"`
Country string `json:"country"`
City string `json:"city"`
}
func getIPInfo(ctx context.Context, client network.Client, ip net.IP) (country, region, city string, err error) {
const baseURL = "https://ipinfo.io/"
url := baseURL + ip.String()
request, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return "", "", "", err
}
b, status, err := client.Do(request)
if err != nil {
return "", "", "", err
} else if status != http.StatusOK {
return "", "", "", fmt.Errorf("%w: %d", errBadHTTPStatus, status)
}
var data ipInfoData
if err := json.Unmarshal(b, &data); err != nil {
return "", "", "", err
}
country, ok := getCountryCodes()[strings.ToLower(data.Country)]
if !ok {
country = data.Country
}
return country, data.Region, data.City, nil
}