dnsupdater/internal/outboundip/ddwrt/iprequester.go

75 lines
1.7 KiB
Go
Raw Normal View History

2020-10-26 09:36:59 +00:00
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
login string
password string
}
func NewIpRequester(statusUrl string, login string, password string) *IpRequester {
return &IpRequester{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 := http.DefaultClient.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
}