go-ddns-client/module/config/config.go

102 lines
1.7 KiB
Go
Raw Normal View History

2019-05-07 09:48:58 +00:00
package config
import (
"errors"
2019-05-08 10:01:06 +00:00
"io/ioutil"
2019-05-07 09:48:58 +00:00
"os"
"path"
"git.trj.tw/golang/utils"
2019-05-08 10:01:06 +00:00
"gopkg.in/yaml.v2"
2019-05-07 09:48:58 +00:00
)
// RecordData -
type RecordData struct {
2019-05-08 14:44:28 +00:00
Name string `yaml:"name" json:"name"`
Type string `yaml:"type" json:"type"`
2019-05-07 09:48:58 +00:00
}
// DomainData -
type DomainData struct {
2019-05-08 14:44:28 +00:00
Name string `yaml:"name" json:"name"`
Records []RecordData `yaml:"records" json:"records"`
2019-05-07 09:48:58 +00:00
}
// Config -
type Config struct {
2019-05-08 14:44:28 +00:00
URL struct {
V4 string `yaml:"v4"`
V6 string `yaml:"v6"`
} `yaml:"url"`
2019-05-07 09:48:58 +00:00
VerifyValue string `yaml:"verify_value"`
Domains []DomainData `yaml:"domains"`
}
2019-05-08 10:01:06 +00:00
var conf *Config
2019-05-07 09:48:58 +00:00
// LoadConfig -
func LoadConfig(p ...string) error {
var fp string
// set config path
if len(p) > 0 && len(p[0]) > 0 {
fp = p[0]
} else {
wd, err := os.Getwd()
if err != nil {
return err
}
fp = path.Join(wd, "config.yml")
}
2019-05-08 10:01:06 +00:00
fp = utils.ParsePath(fp)
2019-05-07 09:48:58 +00:00
if exists := utils.CheckExists(fp, false); !exists {
return errors.New("config file not exists")
}
2019-05-08 10:01:06 +00:00
data, err := ioutil.ReadFile(fp)
if err != nil {
return err
}
conf = &Config{}
err = yaml.Unmarshal(data, conf)
if err != nil {
return err
}
2019-05-07 09:48:58 +00:00
return nil
}
2019-05-08 10:01:06 +00:00
// GetConfig -
func GetConfig() *Config { return conf }
2019-05-08 14:44:28 +00:00
// GetV4Data -
2019-05-09 08:13:25 +00:00
func (p DomainData) GetV4Data() DomainData {
domain := DomainData{}
domain.Name = p.Name
if len(p.Records) == 0 {
return domain
}
for _, it := range p.Records {
if it.Type == "A" {
domain.Records = append(domain.Records, it)
}
}
return domain
}
// GetV6Data -
func (p DomainData) GetV6Data() DomainData {
domain := DomainData{}
domain.Name = p.Name
if len(p.Records) == 0 {
return domain
}
for _, it := range p.Records {
if it.Type == "AAAA" {
domain.Records = append(domain.Records, it)
}
}
return domain
}