/
ali.go
109 lines (93 loc) · 2.65 KB
/
ali.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package ddns
import (
"fmt"
"log"
"os"
"github.com/aliyun/alibaba-cloud-sdk-go/services/alidns"
"github.com/mkxxq/ddns/utils"
)
type AliCredential struct {
AccessKeyID string
AccessKeySecret string
Region string
client *alidns.Client
}
func NewAliCredential(accessKeyID string, accessKeySecret string, region string) *AliCredential {
cre := &AliCredential{AccessKeyID: accessKeyID, AccessKeySecret: accessKeySecret, Region: region}
client, err := cre.newClient()
if err != nil {
log.Panicln(err)
}
cre.client = client
return cre
}
func newAliCredentialWithEnv() (*AliCredential, error) {
region := os.Getenv("ALI_REGION")
if region == "" {
return nil, fmt.Errorf("env value ALI_REGION not define")
}
accessKeyID := os.Getenv("ALI_ACCESS_KEY")
if accessKeyID == "" {
return nil, fmt.Errorf("env value ALI_ACCESS_KEY not define")
}
accessKeySecret := os.Getenv("ALI_SECRET_KEY")
if accessKeySecret == "" {
return nil, fmt.Errorf("env value ALI_SECRET_KEY not define")
}
return NewAliCredential(accessKeyID, accessKeySecret, region), nil
}
func NewAliCredentialWithEnv() *AliCredential {
cre, err := newAliCredentialWithEnv()
if err != nil {
log.Panicln(err)
}
return cre
}
func (cli *AliCredential) newClient() (*alidns.Client, error) {
return alidns.NewClientWithAccessKey(cli.Region, cli.AccessKeyID, cli.AccessKeySecret)
}
func (cli *AliCredential) getRecord(rr string, domain string) (*alidns.Record, error) {
client := cli.client
request := alidns.CreateDescribeSubDomainRecordsRequest()
request.Scheme = "https"
request.SubDomain = fmt.Sprintf("%s.%s", rr, domain)
response, err := client.DescribeSubDomainRecords(request)
if err != nil {
return nil, err
}
for _, record := range response.DomainRecords.Record {
if record.RR == rr && record.DomainName == domain {
return &record, nil
}
}
return nil, fmt.Errorf("can`t found %s.%s record.", rr, domain)
}
func (cli *AliCredential) UpsertRecord(subDomain string, ip string) error {
client := cli.client
rr, domain := utils.DecodeSubDomain(subDomain)
record, err := cli.getRecord(rr, domain)
if err != nil {
request := alidns.CreateAddDomainRecordRequest()
request.Scheme = "https"
request.DomainName = domain
request.Value = ip
request.Type = "A"
request.RR = rr
_, err := client.AddDomainRecord(request)
if err != nil {
return err
}
} else {
request := alidns.CreateUpdateDomainRecordRequest()
request.Scheme = "https"
request.RecordId = record.RecordId
request.RR = record.RR
request.Type = record.Type
request.Value = ip
_, err := client.UpdateDomainRecord(request)
if err != nil {
return err
}
}
return nil
}