package ddns import ( "errors" "io/ioutil" "log" "net/http" "net/textproto" "net/url" "bytes" "git.trj.tw/golang/go-ddns-client/module/config" jsoniter "github.com/json-iterator/go" ) var json = jsoniter.ConfigCompatibleWithStandardLibrary // Errors var ( ErrNoDomain = errors.New("No Domain Setting") ErrAPIResp = errors.New("api call not success") ) // DNSSetting - type DNSSetting struct { V4 []config.DomainData V6 []config.DomainData } // GetDNSSetting - func GetDNSSetting() (DNSSetting, error) { setting := DNSSetting{} conf := config.GetConfig() if len(conf.Domains) == 0 { return setting, ErrNoDomain } 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 } // 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") } 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 }