go-ddns-svc/module/apis/aws/aws.go

122 lines
2.5 KiB
Go
Raw Normal View History

2019-05-02 03:51:48 +00:00
package aws
import (
"errors"
"git.trj.tw/golang/go-ddns-svc/module/config"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/route53"
)
// AWSClient -
type AWSClient struct {
2019-05-02 10:08:39 +00:00
Session *session.Session
Config *aws.Config
R53 *route53.Route53
2019-05-02 03:51:48 +00:00
}
var client *AWSClient
2019-05-02 10:08:39 +00:00
// Error messages
var (
ErrNoClient = errors.New("client not init")
2019-05-02 13:51:30 +00:00
ErrNoZone = errors.New("no hosted zones")
2019-05-02 10:08:39 +00:00
)
2019-05-02 03:51:48 +00:00
// NewAWS -
func NewAWS() error {
conf := config.GetConfig()
awsConf := &aws.Config{}
awsConf.Region = aws.String("us-east-1")
var sess *session.Session
if conf.AWS.SharedConfig {
if len(conf.AWS.SharedName) == 0 {
return errors.New("aws shared config name empty")
}
awsConf.Credentials = credentials.NewSharedCredentials("", conf.AWS.SharedName)
} else {
awsConf.Credentials = credentials.NewStaticCredentials(conf.AWS.AccessKey, conf.AWS.SecretKey, "")
}
sess = session.New(awsConf)
client = &AWSClient{}
client.Session = sess
client.Config = awsConf
2019-05-02 10:08:39 +00:00
client.R53 = route53.New(client.Session)
2019-05-02 03:51:48 +00:00
return nil
}
2019-05-02 10:08:39 +00:00
// ZoneData -
type ZoneData struct {
ID *string
Name string
}
// QueryDomain -
2019-05-02 13:51:30 +00:00
func QueryDomain(name []string) ([]*ZoneData, error) {
if client == nil {
return nil, ErrNoClient
}
domains := make([]string, 0, len(name))
if len(name) == 0 {
return nil, errors.New("no input domain name")
}
for _, n := range name {
if len(n) > 0 {
if n[len(n)-1:] != "." {
n += "."
}
domains = append(domains, n)
}
}
if len(domains) == 0 {
return nil, errors.New("no input domain name")
}
input := &route53.ListHostedZonesInput{}
zoneOut, err := client.R53.ListHostedZones(input)
if err != nil {
return nil, err
}
if len(zoneOut.HostedZones) == 0 {
return nil, ErrNoZone
}
zones := make([]*ZoneData, 0)
for _, it := range zoneOut.HostedZones {
for _, domain := range domains {
if *it.Name == domain {
zone := &ZoneData{
ID: it.Id,
Name: domain,
}
zones = append(zones, zone)
}
}
}
return zones, nil
}
// GetRecord -
func GetRecord(id *string, names []string) (*[]route53.ResourceRecordSet, error) {
if id == nil {
return nil, errors.New("no id input")
}
if len(names) == 0 {
return nil, errors.New("no record names")
}
input := &route53.ListResourceRecordSetsInput{}
input.SetHostedZoneId(*id)
resOut, err := client.R53.ListResourceRecordSets(input)
if err != nil {
return nil, err
}
2019-05-02 10:08:39 +00:00
return nil, nil
}