ip/resolver: make Service.Lookup() accept a context
This commit is contained in:
parent
43705f81d1
commit
ec9056e9e0
6 changed files with 42 additions and 13 deletions
|
|
@ -1,6 +1,7 @@
|
|||
package jsonip
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
|
|
@ -20,8 +21,13 @@ func (s Service) Name() string {
|
|||
return "jsonip"
|
||||
}
|
||||
|
||||
func (s Service) Lookup() (net.IP, error) {
|
||||
resp, err := http.DefaultClient.Get(s.url)
|
||||
func (s Service) Lookup(ctx context.Context) (net.IP, error) {
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", s.url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package jsonip
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
|
|
@ -24,8 +25,21 @@ func TestService_Lookup(t *testing.T) {
|
|||
|
||||
s := Service{url: server.URL}
|
||||
|
||||
ip, err := s.Lookup()
|
||||
ip, err := s.Lookup(context.Background())
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, net.IPv4(211, 46, 32, 214), ip)
|
||||
}
|
||||
|
||||
func TestService_Lookup_HTTPError(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(404)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
s := Service{url: server.URL}
|
||||
|
||||
ip, err := s.Lookup(context.Background())
|
||||
assert.EqualError(t, err, "HTTP Response: 404 Not Found")
|
||||
assert.Nil(t, ip)
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue