go-ddns-client/module/ddns/ddns.go

119 lines
2.2 KiB
Go
Raw Normal View History

2019-05-08 14:44:28 +00:00
package ddns
import (
"errors"
2019-05-09 08:13:25 +00:00
"io/ioutil"
"log"
"net/http"
"net/textproto"
"net/url"
"bytes"
2019-05-08 14:44:28 +00:00
"git.trj.tw/golang/go-ddns-client/module/config"
2019-05-09 08:13:25 +00:00
jsoniter "github.com/json-iterator/go"
2019-05-08 14:44:28 +00:00
)
2019-05-09 08:13:25 +00:00
var json = jsoniter.ConfigCompatibleWithStandardLibrary
2019-05-08 14:44:28 +00:00
// Errors
var (
ErrNoDomain = errors.New("No Domain Setting")
2019-05-09 08:13:25 +00:00
ErrAPIResp = errors.New("api call not success")
2019-05-08 14:44:28 +00:00
)
2019-05-09 08:13:25 +00:00
// DNSSetting -
type DNSSetting struct {
V4 []config.DomainData
V6 []config.DomainData
}
// GetDNSSetting -
func GetDNSSetting() (DNSSetting, error) {
setting := DNSSetting{}
2019-05-08 14:44:28 +00:00
conf := config.GetConfig()
if len(conf.Domains) == 0 {
2019-05-09 08:13:25 +00:00
return setting, ErrNoDomain
2019-05-08 14:44:28 +00:00
}
2019-05-09 08:13:25 +00:00
v4Data := make([]config.DomainData, 0)
v6Data := make([]config.DomainData, 0)
for _, it := range conf.Domains {
v4 := it.GetV4Data()
if len(v4.Records) > 0 {
v4Data = append(v4Data, v4)
}
v6 := it.GetV6Data()
if len(v6.Records) > 0 {
v6Data = append(v6Data, v6)
}
}
setting.V4 = v4Data
setting.V6 = v6Data
return setting, nil
2019-05-08 14:44:28 +00:00
}
2019-05-09 08:13:25 +00:00
// SendRequest -
func SendRequest(v4 bool, data []config.DomainData) error {
conf := config.GetConfig()
var baseURL string
if v4 {
baseURL = conf.URL.V4
} else {
baseURL = conf.URL.V6
}
token := conf.VerifyValue
if len(baseURL) == 0 || len(token) == 0 {
return errors.New("server setting error")
}
2019-05-08 14:44:28 +00:00
2019-05-09 08:13:25 +00:00
body := struct {
Domains []config.DomainData `json:"domains"`
}{}
body.Domains = data
byteData, err := json.Marshal(body)
if err != nil {
return err
}
log.Println("send data :: ", string(byteData))
apiURL, err := url.Parse(baseURL)
if err != nil {
return err
}
apiURL, err = apiURL.Parse("/api/ddns")
if err != nil {
return err
}
reader := bytes.NewReader(byteData)
req, err := http.NewRequest("POST", apiURL.String(), reader)
if err != nil {
return err
}
req.Header.Set(textproto.CanonicalMIMEHeaderKey("X-Mtfos-Key"), token)
req.Header.Set(textproto.CanonicalMIMEHeaderKey("Content-Type"), "application/json")
resp, err := http.DefaultClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
bodyByte, err := ioutil.ReadAll(resp.Body)
if err == nil {
log.Println("body ::: ", string(bodyByte))
}
if resp.StatusCode != 200 {
return ErrAPIResp
}
return nil
2019-05-08 14:44:28 +00:00
}