|
| 1 | +package strato |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "io" |
| 6 | + "net/http" |
| 7 | + "strings" |
| 8 | + |
| 9 | + "github.com/TimothyYe/godns/internal/settings" |
| 10 | + "github.com/TimothyYe/godns/internal/utils" |
| 11 | + log "github.com/sirupsen/logrus" |
| 12 | +) |
| 13 | + |
| 14 | +const ( |
| 15 | + // URL the API address for Strato. |
| 16 | + URL = "https://%s:%[email protected]/nic/update?hostname=%s.%s&myip=%s" |
| 17 | +) |
| 18 | + |
| 19 | +// DNSProvider struct. |
| 20 | +type DNSProvider struct { |
| 21 | + configuration *settings.Settings |
| 22 | +} |
| 23 | + |
| 24 | +// Init passes DNS settings and store it to the provider instance. |
| 25 | +func (provider *DNSProvider) Init(conf *settings.Settings) { |
| 26 | + provider.configuration = conf |
| 27 | +} |
| 28 | + |
| 29 | +func (provider *DNSProvider) UpdateIP(domainName, subdomainName, ip string) error { |
| 30 | + return provider.updateIP(domainName, subdomainName, ip) |
| 31 | +} |
| 32 | + |
| 33 | +// updateIP update subdomain with current IP. |
| 34 | +func (provider *DNSProvider) updateIP(domain, subDomain, currentIP string) error { |
| 35 | + client := utils.GetHTTPClient(provider.configuration) |
| 36 | + resp, err := client.Get(fmt.Sprintf(URL, |
| 37 | + domain, |
| 38 | + provider.configuration.Password, |
| 39 | + subDomain, |
| 40 | + domain, |
| 41 | + currentIP)) |
| 42 | + |
| 43 | + if err != nil { |
| 44 | + // handle error |
| 45 | + log.Error("Failed to update sub domain:", subDomain) |
| 46 | + return err |
| 47 | + } |
| 48 | + |
| 49 | + defer func(Body io.ReadCloser) { |
| 50 | + err := Body.Close() |
| 51 | + if err != nil { |
| 52 | + log.Error(err) |
| 53 | + } |
| 54 | + }(resp.Body) |
| 55 | + |
| 56 | + if err != nil { |
| 57 | + log.Error("Err:", err.Error()) |
| 58 | + return err |
| 59 | + } |
| 60 | + |
| 61 | + body, _ := io.ReadAll(resp.Body) |
| 62 | + if resp.StatusCode != http.StatusOK { |
| 63 | + log.Errorf("Update IP failed: %s", string(body)) |
| 64 | + return fmt.Errorf("update IP failed: %s", string(body)) |
| 65 | + } |
| 66 | + |
| 67 | + if strings.Contains(string(body), "good") { |
| 68 | + log.Infof("Update IP success: %s", string(body)) |
| 69 | + } else if strings.Contains(string(body), "nochg") { |
| 70 | + log.Infof("IP not changed: %s", string(body)) |
| 71 | + } else { |
| 72 | + return fmt.Errorf("update IP failed: %s", string(body)) |
| 73 | + } |
| 74 | + |
| 75 | + return nil |
| 76 | +} |
0 commit comments