77 lines
1.7 KiB
Go
77 lines
1.7 KiB
Go
package ddwrt
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"net/http"
|
|
"regexp"
|
|
|
|
"github.com/pkg/errors"
|
|
"gitlab.lehouerou.net/laurent/dnsupdater/internal/outboundip"
|
|
)
|
|
|
|
const (
|
|
DefaultUrl = "http://192.168.1.1/Status_Internet.live.asp"
|
|
WanIpRegex = "wan_ipaddr::([0-9.]*)}"
|
|
)
|
|
|
|
type IpRequester struct {
|
|
StatusUrl string
|
|
|
|
client *http.Client
|
|
login string
|
|
password string
|
|
}
|
|
|
|
func NewIpRequester(client *http.Client, statusUrl string, login string, password string) *IpRequester {
|
|
return &IpRequester{client: client, StatusUrl: statusUrl, login: login, password: password}
|
|
}
|
|
|
|
func (r IpRequester) GetOutboundIp() <-chan outboundip.IpRequestResult {
|
|
result := make(chan outboundip.IpRequestResult)
|
|
go func() {
|
|
defer close(result)
|
|
url := r.StatusUrl
|
|
if url == "" {
|
|
url = DefaultUrl
|
|
}
|
|
req, err := http.NewRequest("GET", url, nil)
|
|
if err != nil {
|
|
result <- outboundip.IpRequestResult{
|
|
Error: errors.Wrap(err, "creating http request"),
|
|
}
|
|
return
|
|
}
|
|
|
|
if r.login != "" && r.password != "" {
|
|
req.SetBasicAuth(r.login, r.password)
|
|
}
|
|
|
|
res, err := r.client.Do(req)
|
|
if err != nil {
|
|
result <- outboundip.IpRequestResult{
|
|
Error: errors.Wrap(err, "executing http request"),
|
|
}
|
|
return
|
|
}
|
|
defer res.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(res.Body)
|
|
if err != nil {
|
|
result <- outboundip.IpRequestResult{
|
|
Error: errors.Wrap(err, "reading response body"),
|
|
}
|
|
return
|
|
}
|
|
|
|
matches := regexp.MustCompile(WanIpRegex).FindStringSubmatch(string(body))
|
|
if len(matches) < 2 {
|
|
result <- outboundip.IpRequestResult{
|
|
Error: errors.Errorf("unable to find WAN IP with regex %s in %s", WanIpRegex, string(body)),
|
|
}
|
|
return
|
|
}
|
|
result <- outboundip.IpRequestResult{Ip: matches[1]}
|
|
}()
|
|
return result
|
|
}
|