Code maintenance: use native Go HTTP client
This commit is contained in:
8
internal/publicip/errors.go
Normal file
8
internal/publicip/errors.go
Normal file
@@ -0,0 +1,8 @@
|
||||
package publicip
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrBadStatusCode = errors.New("bad HTTP status")
|
||||
ErrCannotReadBody = errors.New("cannot read response body")
|
||||
)
|
||||
@@ -3,6 +3,7 @@ package publicip
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
@@ -11,7 +12,6 @@ import (
|
||||
"github.com/qdm12/gluetun/internal/os"
|
||||
"github.com/qdm12/gluetun/internal/settings"
|
||||
"github.com/qdm12/golibs/logging"
|
||||
"github.com/qdm12/golibs/network"
|
||||
)
|
||||
|
||||
type Looper interface {
|
||||
@@ -45,7 +45,7 @@ type looper struct {
|
||||
timeSince func(time.Time) time.Duration
|
||||
}
|
||||
|
||||
func NewLooper(client network.Client, logger logging.Logger,
|
||||
func NewLooper(client *http.Client, logger logging.Logger,
|
||||
settings settings.PublicIP, uid, gid int,
|
||||
os os.OS) Looper {
|
||||
return &looper{
|
||||
|
||||
@@ -3,12 +3,11 @@ package publicip
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/qdm12/golibs/network"
|
||||
)
|
||||
|
||||
type IPGetter interface {
|
||||
@@ -16,11 +15,11 @@ type IPGetter interface {
|
||||
}
|
||||
|
||||
type ipGetter struct {
|
||||
client network.Client
|
||||
client *http.Client
|
||||
randIntn func(n int) int
|
||||
}
|
||||
|
||||
func NewIPGetter(client network.Client) IPGetter {
|
||||
func NewIPGetter(client *http.Client) IPGetter {
|
||||
return &ipGetter{
|
||||
client: client,
|
||||
randIntn: rand.Intn,
|
||||
@@ -39,12 +38,27 @@ func (i *ipGetter) Get(ctx context.Context) (ip net.IP, err error) {
|
||||
"https://ipinfo.io/ip",
|
||||
}
|
||||
url := urls[i.randIntn(len(urls))]
|
||||
content, status, err := i.client.Get(ctx, url, network.UseRandomUserAgent())
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
} else if status != http.StatusOK {
|
||||
return nil, fmt.Errorf("received unexpected status code %d from %s", status, url)
|
||||
}
|
||||
|
||||
response, err := i.client.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("%w from %s: %s", ErrBadStatusCode, url, response.Status)
|
||||
}
|
||||
|
||||
content, err := ioutil.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: %s", ErrCannotReadBody, err)
|
||||
}
|
||||
|
||||
s := strings.ReplaceAll(string(content), "\n", "")
|
||||
ip = net.ParseIP(s)
|
||||
if ip == nil {
|
||||
|
||||
Reference in New Issue
Block a user