mirror of
https://github.com/qdm12/gluetun.git
synced 2026-05-10 04:30:20 +02:00
Feature: log out country, region and city of IP
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
package publicip
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/qdm12/gluetun/internal/constants"
|
||||
)
|
||||
|
||||
type ipInfoData struct {
|
||||
Region string `json:"region"`
|
||||
Country string `json:"country"`
|
||||
City string `json:"city"`
|
||||
}
|
||||
|
||||
var ErrBadHTTPStatus = errors.New("bad HTTP status received")
|
||||
|
||||
func Info(ctx context.Context, client *http.Client, ip net.IP) ( //nolint:interfacer
|
||||
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
|
||||
}
|
||||
|
||||
response, err := client.Do(request)
|
||||
if err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return "", "", "", fmt.Errorf("%w: %d", ErrBadHTTPStatus, response.StatusCode)
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(response.Body)
|
||||
var data ipInfoData
|
||||
if err := decoder.Decode(&data); err != nil {
|
||||
return "", "", "", err
|
||||
}
|
||||
|
||||
countryCode := strings.ToLower(data.Country)
|
||||
country, ok := constants.CountryCodes()[countryCode]
|
||||
if !ok {
|
||||
country = data.Country
|
||||
}
|
||||
return country, data.Region, data.City, nil
|
||||
}
|
||||
@@ -28,6 +28,7 @@ type looper struct {
|
||||
state state
|
||||
// Objects
|
||||
getter IPGetter
|
||||
client *http.Client
|
||||
logger logging.Logger
|
||||
os os.OS
|
||||
// Fixed settings
|
||||
@@ -57,6 +58,7 @@ func NewLooper(client *http.Client, logger logging.Logger,
|
||||
settings: settings,
|
||||
},
|
||||
// Objects
|
||||
client: client,
|
||||
getter: NewIPGetter(client),
|
||||
logger: logger.WithPrefix("ip getter: "),
|
||||
os: os,
|
||||
@@ -150,8 +152,17 @@ func (l *looper) Run(ctx context.Context, wg *sync.WaitGroup) {
|
||||
case ip := <-ipCh:
|
||||
getCancel()
|
||||
l.state.setPublicIP(ip)
|
||||
l.logger.Info("Public IP address is %s", ip)
|
||||
err := persistPublicIP(l.os.OpenFile, l.state.settings.IPFilepath,
|
||||
|
||||
message := "Public IP address is " + ip.String()
|
||||
country, region, city, err := Info(ctx, l.client, ip)
|
||||
if err != nil {
|
||||
l.logger.Warn(err)
|
||||
} else {
|
||||
message += " (" + country + ", " + region + ", " + city + ")"
|
||||
}
|
||||
l.logger.Info(message)
|
||||
|
||||
err = persistPublicIP(l.os.OpenFile, l.state.settings.IPFilepath,
|
||||
ip.String(), l.puid, l.pgid)
|
||||
if err != nil {
|
||||
l.logger.Error(err)
|
||||
|
||||
Reference in New Issue
Block a user