Initial commit
This commit is contained in:
commit
f57d355631
27 changed files with 1315 additions and 0 deletions
39
ip/resolver/jsonip/service.go
Normal file
39
ip/resolver/jsonip/service.go
Normal file
|
|
@ -0,0 +1,39 @@
|
|||
package jsonip
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
url string
|
||||
}
|
||||
|
||||
func New() *Service {
|
||||
return &Service{
|
||||
url: "https://jsonip.com",
|
||||
}
|
||||
}
|
||||
|
||||
func (s Service) Name() string {
|
||||
return "jsonip"
|
||||
}
|
||||
|
||||
func (s Service) Lookup() (net.IP, error) {
|
||||
resp, err := http.DefaultClient.Get(s.url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var v struct {
|
||||
Ip string `json:"ip"`
|
||||
Location string `json:"geo-ip"`
|
||||
Help string `json:"API Help"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return net.ParseIP(v.Ip), err
|
||||
}
|
||||
31
ip/resolver/jsonip/service_test.go
Normal file
31
ip/resolver/jsonip/service_test.go
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
package jsonip
|
||||
|
||||
import (
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestService_Name(t *testing.T) {
|
||||
s := Service{}
|
||||
|
||||
assert.Equal(t, "jsonip", s.Name())
|
||||
}
|
||||
|
||||
func TestService_Lookup(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, err := w.Write([]byte(`{"ip":"211.46.32.214","geo-ip":"https://getjsonip.com/#plus","API Help":"https://getjsonip.com/#docs"}`))
|
||||
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(211, 46, 32, 214), ip)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue