feat: add yaml config support

This commit is contained in:
loveuer
2025-03-20 11:55:47 +08:00
parent 32b30ae183
commit 2e13671bb7
9 changed files with 139 additions and 145 deletions

View File

@ -1,71 +1,69 @@
package opt
import (
"encoding/json"
"fmt"
"github.com/loveuer/nf/nft/log"
"os"
"github.com/spf13/viper"
"ultone/internal/tool"
)
type listen struct {
Http string `json:"http"`
Grpc string `json:"grpc"`
Http string `mapstructure:"http"`
Grpc string `mapstructure:"grpc"`
}
type db struct {
Type string `json:"-"` // postgres, mysql, sqlite
Uri string `json:"uri"`
Type string `mapstructure:"-"` // postgres, mysql, sqlite
Uri string `mapstructure:"uri"`
}
type cache struct {
Uri string `json:"uri"`
Uri string `mapstructure:"uri"`
}
type es struct {
Uri string `json:"uri"`
Uri string `mapstructure:"uri"`
Index struct {
Staff string `json:"staff"`
} `json:"index"`
Staff string `mapstructure:"staff"`
} `mapstructure:"index"`
}
type Nebula struct {
Uri string `json:"uri"`
Username string `json:"username"`
Password string `json:"password"`
Space string `json:"space"`
Uri string `mapstructure:"uri"`
Username string `mapstructure:"username"`
Password string `mapstructure:"password"`
Space string `mapstructure:"space"`
}
type config struct {
Name string `json:"name"`
Listen listen `json:"listen"`
DB db `json:"db"`
Cache cache `json:"cache"`
ES es `json:"es"`
Nebula Nebula `json:"nebula"`
Name string `mapstructure:"name"`
Debug bool `mapstructure:"-"`
Listen listen `mapstructure:"listen"`
DB db `mapstructure:"db"`
Cache cache `mapstructure:"cache"`
ES es `mapstructure:"es"`
Nebula Nebula `mapstructure:"nebula"`
}
var (
Debug bool
Mode string
Cfg = &config{}
Cfg = &config{}
)
func Init(filename string) error {
var (
err error
bs []byte
)
log.Info("opt.Init: start reading config file: %s", filename)
if bs, err = os.ReadFile(filename); err != nil {
return fmt.Errorf("opt.Init: read config file=%s err=%v", filename, err)
viper.SetConfigFile(filename)
if err = viper.ReadInConfig(); err != nil {
return fmt.Errorf("opt.Init: readin config failed, err = %s", err.Error())
}
if err = json.Unmarshal(bs, Cfg); err != nil {
return fmt.Errorf("opt.Init: json marshal config=%s err=%v", string(bs), err)
if err = viper.Unmarshal(Cfg); err != nil {
return fmt.Errorf("opt.Init: unmarshal config failed, err = %s", err.Error())
}
tool.TablePrinter(Cfg)