Added getting of external IP address

This commit is contained in:
Mike Cheng 2015-05-02 21:56:08 -04:00
parent 3e5e8b4478
commit d7ed09175c
2 changed files with 87 additions and 0 deletions

38
dyndns/external.go Normal file
View File

@ -0,0 +1,38 @@
package dyndns
import (
"errors"
"io/ioutil"
"net/http"
)
var (
Urls = []string{"http://myexternalip.com/raw"}
)
func tryMirror(url string) (string, error) {
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(contents), nil
}
// Retrieves the external facing IP Address
func GetExternalIP() (string, error) {
for _, url := range Urls {
resp, err := tryMirror(url)
if err == nil {
return resp, err
}
}
return "", errors.New("Could not retreive external IP")
}

49
dyndns/external_test.go Normal file
View File

@ -0,0 +1,49 @@
package dyndns
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
)
func testServerHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.String() == "/correct" {
w.Write([]byte("Correct"))
} else {
w.Write([]byte("Incorrect"))
}
}
func TestGetExternalIP(t *testing.T) {
// Setup local HTTP server to emulate external IP services.
server := httptest.NewServer(http.HandlerFunc(testServerHandler))
defer server.Close()
// In order to test the failover, we
// provide 2 bad IPs, and 2 correct ones,
// in that order.
Urls = make([]string, 4)
Urls[0] = ""
Urls[1] = "1.4.5.6"
Urls[2] = fmt.Sprintf("%s/%s", server.URL, "correct")
Urls[3] = fmt.Sprintf("%s/%s", server.URL, "incorrect")
resp, err := GetExternalIP()
if err != nil {
t.Fatal(err)
}
if resp != "Correct" {
t.Fatal("Incorrect result returned:", resp)
}
}
func TestGetExternalIPFailure(t *testing.T) {
Urls = make([]string, 1)
Urls[0] = ""
_, err := GetExternalIP()
if err == nil {
t.Fatal("Should have returned error when no service can be reached")
}
}