github.com/TeaOSLab/EdgeNode@v1.3.8/internal/configs/api_config.go (about) 1 package configs 2 3 import ( 4 "errors" 5 "github.com/iwind/TeaGo/Tea" 6 "gopkg.in/yaml.v3" 7 "os" 8 ) 9 10 const ConfigFileName = "api_node.yaml" 11 const oldConfigFileName = "api.yaml" 12 13 type APIConfig struct { 14 OldRPC struct { 15 Endpoints []string `yaml:"endpoints,omitempty" json:"endpoints"` 16 DisableUpdate bool `yaml:"disableUpdate,omitempty" json:"disableUpdate"` 17 } `yaml:"rpc,omitempty" json:"rpc"` 18 19 RPCEndpoints []string `yaml:"rpc.endpoints,flow" json:"rpc.endpoints"` 20 RPCDisableUpdate bool `yaml:"rpc.disableUpdate" json:"rpc.disableUpdate"` 21 NodeId string `yaml:"nodeId" json:"nodeId"` 22 Secret string `yaml:"secret" json:"secret"` 23 } 24 25 func NewAPIConfig() *APIConfig { 26 return &APIConfig{} 27 } 28 29 func (this *APIConfig) Init() error { 30 // compatible with old 31 if len(this.RPCEndpoints) == 0 && len(this.OldRPC.Endpoints) > 0 { 32 this.RPCEndpoints = this.OldRPC.Endpoints 33 this.RPCDisableUpdate = this.OldRPC.DisableUpdate 34 } 35 36 if len(this.RPCEndpoints) == 0 { 37 return errors.New("no valid 'rpc.endpoints'") 38 } 39 40 if len(this.NodeId) == 0 { 41 return errors.New("'nodeId' required") 42 } 43 if len(this.Secret) == 0 { 44 return errors.New("'secret' required") 45 } 46 return nil 47 } 48 49 func LoadAPIConfig() (*APIConfig, error) { 50 for _, filename := range []string{ConfigFileName, oldConfigFileName} { 51 data, err := os.ReadFile(Tea.ConfigFile(filename)) 52 if err != nil { 53 if os.IsNotExist(err) { 54 continue 55 } 56 return nil, err 57 } 58 59 var config = &APIConfig{} 60 err = yaml.Unmarshal(data, config) 61 if err != nil { 62 return nil, err 63 } 64 65 err = config.Init() 66 if err != nil { 67 return nil, errors.New("init error: " + err.Error()) 68 } 69 70 // 自动生成新的配置文件 71 if filename == oldConfigFileName { 72 config.OldRPC.Endpoints = nil 73 _ = config.WriteFile(Tea.ConfigFile(ConfigFileName)) 74 } 75 76 return config, nil 77 } 78 return nil, errors.New("no config file '" + ConfigFileName + "' found") 79 } 80 81 // WriteFile 保存到文件 82 func (this *APIConfig) WriteFile(path string) error { 83 data, err := yaml.Marshal(this) 84 if err != nil { 85 return err 86 } 87 err = os.WriteFile(path, data, 0666) 88 return err 89 }