Files
EdgeNode/internal/configs/api_config.go

84 lines
1.9 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
)
2023-08-12 15:08:22 +08:00
const ConfigFileName = "api_node.yaml"
const oldConfigFileName = "api.yaml"
2020-07-22 22:18:47 +08:00
type APIConfig struct {
2023-08-12 15:08:22 +08:00
OldRPC struct {
Endpoints []string `yaml:"endpoints" json:"endpoints"`
DisableUpdate bool `yaml:"disableUpdate" json:"disableUpdate"`
} `yaml:"rpc" json:"rpc"`
2023-08-12 15:08:22 +08:00
RPCEndpoints []string `yaml:"rpc.endpoints" json:"rpc.endpoints"`
RPCDisableUpdate bool `yaml:"rpc.disableUpdate" json:"rpc.disableUpdate"`
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 {
2023-08-12 15:08:22 +08:00
// compatible with old
if len(this.RPCEndpoints) == 0 && len(this.OldRPC.Endpoints) > 0 {
this.RPCEndpoints = this.OldRPC.Endpoints
this.RPCDisableUpdate = this.OldRPC.DisableUpdate
}
if len(this.RPCEndpoints) == 0 {
return errors.New("no valid 'rpc.endpoints'")
}
2023-08-12 15:08:22 +08:00
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) {
2023-08-12 15:08:22 +08:00
for _, filename := range []string{ConfigFileName, oldConfigFileName} {
data, err := os.ReadFile(Tea.ConfigFile(filename))
if err != nil {
if os.IsNotExist(err) {
continue
}
return nil, err
}
2020-07-22 22:18:47 +08:00
2023-08-12 15:08:22 +08:00
var config = &APIConfig{}
err = yaml.Unmarshal(data, config)
if err != nil {
return nil, err
}
2020-07-22 22:18:47 +08:00
2023-08-12 15:08:22 +08:00
err = config.Init()
if err != nil {
return nil, errors.New("init error: " + err.Error())
}
2023-08-12 15:08:22 +08:00
return config, nil
}
return nil, errors.New("no config file '" + ConfigFileName + "' found")
2020-07-22 22:18:47 +08:00
}
// 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
}