feat(config): 本地config文件缺失时使用默认配置
This commit is contained in:
@@ -1,8 +1,9 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
|
||||
"fmt"
|
||||
"os"
|
||||
"errors"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
@@ -40,15 +41,54 @@ type RabbitMQConfig struct {
|
||||
}
|
||||
|
||||
func Load(filename string) (Config, error) {
|
||||
data, err := ioutil.ReadFile(filename)
|
||||
data, err := os.ReadFile(filename)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
return Config{}, fmt.Errorf("failed to read config file: %w", err)
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := yaml.Unmarshal(data, &cfg); err != nil {
|
||||
return Config{}, err
|
||||
return Config{}, fmt.Errorf("parse config %s: %w", filename, err)
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
// bool用来表示是否使用了默认配置,true表示使用了默认配置
|
||||
func LoadLocalDev(filename string) (Config, bool, error) {
|
||||
cfg, err := Load(filename)
|
||||
if err == nil {
|
||||
return cfg, false, nil
|
||||
}
|
||||
if errors.Is(err, os.ErrNotExist) {
|
||||
return DefaultLocalConfig(), true, nil
|
||||
}
|
||||
return Config{}, false, err
|
||||
}
|
||||
|
||||
func DefaultLocalConfig() Config {
|
||||
return Config{
|
||||
Server: ServerConfig{
|
||||
Port: 8080,
|
||||
},
|
||||
Database: DatabaseConfig{
|
||||
Host: "localhost",
|
||||
Port: 3306,
|
||||
User: "root",
|
||||
Password: "123456",
|
||||
DBName: "feedsystem",
|
||||
},
|
||||
Redis: RedisConfig{
|
||||
Host: "localhost",
|
||||
Port: 6379,
|
||||
Password: "123456",
|
||||
DB: 0,
|
||||
},
|
||||
RabbitMQ: RabbitMQConfig{
|
||||
Host: "localhost",
|
||||
Port: 5672,
|
||||
Username: "admin",
|
||||
Password: "password123",
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user