Files
EdgeNode/internal/configs/api_config.go

66 lines
1.3 KiB
Go
Raw Normal View History

2020-07-22 22:18:47 +08:00
package configs
import (
"errors"
2020-07-22 22:18:47 +08:00
"github.com/iwind/TeaGo/Tea"
2022-03-04 12:30:06 +08:00
"gopkg.in/yaml.v3"
2022-08-04 11:34:06 +08:00
"os"
2020-07-22 22:18:47 +08:00
)
2022-03-04 12:30:06 +08:00
// APIConfig 节点API配置
2020-07-22 22:18:47 +08:00
type APIConfig struct {
RPC struct {
Endpoints []string `yaml:"endpoints" json:"endpoints"`
DisableUpdate bool `yaml:"disableUpdate" json:"disableUpdate"`
} `yaml:"rpc" json:"rpc"`
NodeId string `yaml:"nodeId" json:"nodeId"`
Secret string `yaml:"secret" json:"secret"`
}
func NewAPIConfig() *APIConfig {
return &APIConfig{}
2020-07-22 22:18:47 +08:00
}
func (this *APIConfig) Init() error {
if len(this.RPC.Endpoints) == 0 {
return errors.New("no valid 'rpc.endpoints'")
}
if len(this.NodeId) == 0 {
return errors.New("'nodeId' required")
}
if len(this.Secret) == 0 {
return errors.New("'secret' required")
}
return nil
}
2020-07-22 22:18:47 +08:00
func LoadAPIConfig() (*APIConfig, error) {
2022-08-04 11:34:06 +08:00
data, err := os.ReadFile(Tea.ConfigFile("api.yaml"))
2020-07-22 22:18:47 +08:00
if err != nil {
return nil, err
}
var config = &APIConfig{}
2020-07-22 22:18:47 +08:00
err = yaml.Unmarshal(data, config)
if err != nil {
return nil, err
}
err = config.Init()
if err != nil {
return nil, errors.New("init error: " + err.Error())
}
2020-07-22 22:18:47 +08:00
return config, nil
}
// WriteFile 保存到文件
func (this *APIConfig) WriteFile(path string) error {
data, err := yaml.Marshal(this)
if err != nil {
return err
}
2022-08-04 11:34:06 +08:00
err = os.WriteFile(path, data, 0666)
return err
}