Files
ddns-updater/public_resolvers/ifconfigme.go

63 lines
1.1 KiB
Go
Raw Normal View History

2023-04-28 14:57:21 +02:00
package public_resolvers
import (
"context"
"fmt"
"io"
"net"
"net/http"
2023-04-29 12:45:21 +02:00
"time"
2023-04-28 14:57:21 +02:00
)
const (
IfConfigMeTag = "ifconfig.me"
)
type Doer interface {
Do(*http.Request) (*http.Response, error)
}
var (
ifConfigMeUrl = "https://ifconfig.me"
)
type IfConfigMe struct {
client Doer
}
2023-04-29 12:45:21 +02:00
func NewDefaultIfConfigMe() *IfConfigMe {
return NewIfConfigMe(&http.Client{
Timeout: 10 * time.Second,
})
}
2023-04-28 14:57:21 +02:00
func NewIfConfigMe(c Doer) *IfConfigMe {
return &IfConfigMe{client: c}
}
func (i IfConfigMe) ResolvePublicIp(ctx context.Context) (net.IP, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, ifConfigMeUrl, nil)
if err != nil {
return net.IP{}, fmt.Errorf("error creating ifconfig request: %w", err)
}
resp, err := i.client.Do(req)
if err != nil {
return net.IP{}, err
}
2023-04-29 12:45:21 +02:00
defer func() {
_ = resp.Body.Close()
}()
2023-04-28 14:57:21 +02:00
if resp.StatusCode != http.StatusOK {
return net.IP{}, fmt.Errorf("unexpected response code %d", resp.StatusCode)
}
ipText, err := io.ReadAll(resp.Body)
if err != nil {
return net.IP{}, fmt.Errorf("error reading body: %w", err)
}
return net.ParseIP(string(ipText)), nil
}