go-ddns-client/module/config/config.go
2019-05-09 16:13:25 +08:00

102 lines
1.7 KiB
Go

package config
import (
"errors"
"io/ioutil"
"os"
"path"
"git.trj.tw/golang/utils"
"gopkg.in/yaml.v2"
)
// RecordData -
type RecordData struct {
Name string `yaml:"name" json:"name"`
Type string `yaml:"type" json:"type"`
}
// DomainData -
type DomainData struct {
Name string `yaml:"name" json:"name"`
Records []RecordData `yaml:"records" json:"records"`
}
// Config -
type Config struct {
URL struct {
V4 string `yaml:"v4"`
V6 string `yaml:"v6"`
} `yaml:"url"`
VerifyValue string `yaml:"verify_value"`
Domains []DomainData `yaml:"domains"`
}
var conf *Config
// 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")
}
fp = utils.ParsePath(fp)
if exists := utils.CheckExists(fp, false); !exists {
return errors.New("config file not exists")
}
data, err := ioutil.ReadFile(fp)
if err != nil {
return err
}
conf = &Config{}
err = yaml.Unmarshal(data, conf)
if err != nil {
return err
}
return nil
}
// GetConfig -
func GetConfig() *Config { return conf }
// GetV4Data -
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
}