-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcfapi.go
112 lines (91 loc) · 2.21 KB
/
cfapi.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
110
111
112
package main
import (
"encoding/json"
"fmt"
"net/http"
)
var cfHeader http.Header
var cfDnsApiUrl string
func GetCFRecordIP(domain string, recordType string) (string, error) {
var result ListDnsRecordResp
resp, err := httpGetRequest(fmt.Sprintf("%s?type=%s&name=%s", cfDnsApiUrl, recordType, domain), cfHeader, 0)
if err != nil {
goto ERROR
}
err = json.NewDecoder(resp.Body).Decode(&result)
resp.Body.Close()
if err != nil {
goto ERROR
}
if !result.Success {
err = fmt.Errorf("cloudflare api return unsuccess")
goto ERROR
}
for _, record := range result.Result {
if record.Name == domain {
return record.Content, nil
}
}
err = fmt.Errorf("domain record content not found")
ERROR:
return "", err
}
func UpdateCFRecord(domain CFRecord, recordType string, ip string) error {
var result UpdateDnsRecordResp
data := UpdateDnsRecordReq{
Type: recordType,
Name: domain.Name,
Content: ip,
TTL: 60,
Proxied: false,
}
jsonString, err := json.Marshal(data)
if err != nil {
return err
}
resp, err := cfapiPutRequest(fmt.Sprintf("%s/%s", cfDnsApiUrl, domain.RecordID), jsonString)
if err != nil {
return err
}
err = json.NewDecoder(resp.Body).Decode(&result)
resp.Body.Close()
if err != nil {
return err
}
if !result.Success {
return fmt.Errorf("cloudflare api return unsuccess")
}
return nil
}
func generateUrlAndHeader(config *Config) {
cfHeader = http.Header{
"X-Auth-Email": {config.Email},
"X-Auth-Key": {config.APIKey},
"cache-control": {"no-cache"},
}
cfDnsApiUrl = fmt.Sprintf("https://api.cloudflare.com/client/v4/zones/%s/dns_records", config.Zones)
}
func getDnsRecordId(domain string, recordType string) (string, error) {
var result ListDnsRecordResp
resp, err := httpGetRequest(fmt.Sprintf("%s?type=%s&name=%s", cfDnsApiUrl, recordType, domain), cfHeader, 0)
if err != nil {
goto ERR
}
err = json.NewDecoder(resp.Body).Decode(&result)
resp.Body.Close()
if err != nil {
goto ERR
}
if !result.Success {
err = fmt.Errorf("cloudflare api return unsuccess")
goto ERR
}
for _, record := range result.Result {
if record.Name == domain {
return record.Id, nil
}
}
err = fmt.Errorf("domain record id not found")
ERR:
return "", err
}