-
Notifications
You must be signed in to change notification settings - Fork 2
/
digitalocean.go
74 lines (65 loc) · 1.64 KB
/
digitalocean.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package dyndns
import (
"context"
"strings"
"golang.org/x/oauth2"
"github.com/digitalocean/godo"
)
type tokenSource struct {
AccessToken string
}
func (t *tokenSource) Token() (*oauth2.Token, error) {
token := &oauth2.Token{
AccessToken: t.AccessToken,
}
return token, nil
}
func digitaloceanupd(configs Config) error {
tokenSource := &tokenSource{
AccessToken: configs.Auth.Apikey,
}
oauthClient := oauth2.NewClient(context.Background(), tokenSource)
client := godo.NewClient(oauthClient)
ctx := context.TODO()
for _, domainName := range configs.Domains {
// split domain
domainArray := strings.Split(domainName, ".")
domain := domainArray[len(domainArray)-2] + "." + domainArray[len(domainArray)-1]
var subDomain string
if len(domainArray) > 2 {
subDomain = domainName[:len(domainName)-len(domain)-1]
}
// get origin records
records, _, err := client.Domains.Records(ctx, domain, nil)
if err != nil {
return err
}
var record *godo.DomainRecord
for i := 0; i < len(records); i++ {
if records[i].Name == subDomain {
record = &records[i]
break
}
}
if record == nil {
_, _, err = client.Domains.CreateRecord(ctx, domain, &godo.DomainRecordEditRequest{
Type: "A",
Name: subDomain,
Data: configs.Ipupdate,
})
if err != nil {
return err
}
} else if configs.Ipupdate != record.Data {
_, _, err = client.Domains.EditRecord(ctx, domain, record.ID, &godo.DomainRecordEditRequest{
Type: "A",
Name: subDomain,
Data: configs.Ipupdate,
})
if err != nil {
return err
}
}
}
return nil
}