mirror of
https://gitlab.com/pnx-tools/dns-updater.git
synced 2026-06-16 05:54:56 +02:00
Adding ip/resolver/basic_http
This commit is contained in:
parent
9f344a2ae9
commit
2ddf2dadd7
2 changed files with 95 additions and 0 deletions
42
ip/resolver/basic_http/service.go
Normal file
42
ip/resolver/basic_http/service.go
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
package basic_http
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
ServiceName string
|
||||
Url string
|
||||
Headers http.Header
|
||||
}
|
||||
|
||||
func (s Service) Name() string {
|
||||
return s.ServiceName
|
||||
}
|
||||
|
||||
func (s Service) Lookup() (net.IP, error) {
|
||||
req, err := http.NewRequest("GET", s.Url, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header = s.Headers
|
||||
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Trim spaces and stuff.
|
||||
ip_str := strings.TrimSpace(string(body))
|
||||
|
||||
return net.ParseIP(ip_str), err
|
||||
}
|
||||
53
ip/resolver/basic_http/service_test.go
Normal file
53
ip/resolver/basic_http/service_test.go
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
package basic_http
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestService_Name(t *testing.T) {
|
||||
s := Service{ServiceName: "my_service"}
|
||||
|
||||
assert.Equal(t, "my_service", s.Name())
|
||||
}
|
||||
|
||||
func TestService_Lookup(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := w.Write([]byte("255.240.85.2"))
|
||||
assert.NoError(t, err)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
s := Service{Url: server.URL}
|
||||
|
||||
ip, err := s.Lookup()
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, net.IPv4(255, 240, 85, 2), ip)
|
||||
}
|
||||
|
||||
func TestService_Lookup_WithHeaders(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
assert.Equal(t, "application/json", r.Header.Get("Content-Type"))
|
||||
|
||||
_, err := w.Write([]byte("125.74.233.13"))
|
||||
assert.NoError(t, err)
|
||||
}))
|
||||
defer server.Close()
|
||||
|
||||
s := Service{
|
||||
Url: server.URL,
|
||||
Headers: http.Header{
|
||||
"Content-Type": []string{"application/json"},
|
||||
},
|
||||
}
|
||||
|
||||
ip, err := s.Lookup()
|
||||
assert.NoError(t, err)
|
||||
|
||||
assert.Equal(t, net.IPv4(125, 74, 233, 13), ip)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue