Code maintenance: use native Go HTTP client

This commit is contained in:
Quentin McGaw
2020-12-29 02:55:34 +00:00
parent 60e98235ca
commit 8d5f2fec09
11 changed files with 379 additions and 122 deletions

View File

@@ -0,0 +1,8 @@
package publicip
import "errors"
var (
ErrBadStatusCode = errors.New("bad HTTP status")
ErrCannotReadBody = errors.New("cannot read response body")
)

View File

@@ -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{

View File

@@ -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 {