first commit
This commit is contained in:
64
config/config.go
Normal file
64
config/config.go
Normal file
@@ -0,0 +1,64 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/sirupsen/logrus"
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type SqliteConfig struct {
|
||||
Dbname string `yaml:"dbname"`
|
||||
Debug bool `yaml:"debug"`
|
||||
}
|
||||
|
||||
type ServerConfig struct {
|
||||
ServerName string `yaml:"server-name"`
|
||||
ServerListen string `yaml:"server-listen"`
|
||||
Environment string `yaml:"environment"`
|
||||
DBConfig SqliteConfig `yaml:"db"`
|
||||
}
|
||||
|
||||
type ServerConf struct {
|
||||
ConfigFile string
|
||||
ServerConfig `yaml:",inline"`
|
||||
}
|
||||
|
||||
var conf *ServerConf
|
||||
|
||||
func New(fileName string) {
|
||||
conf = new(ServerConf)
|
||||
conf.ConfigFile = fileName
|
||||
if err := conf.Load(); err != nil {
|
||||
logrus.Fatalf("read config file failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func Get() *ServerConf {
|
||||
if conf == nil {
|
||||
panic("config file not initialized")
|
||||
}
|
||||
return conf
|
||||
}
|
||||
|
||||
func (receiver *ServerConf) Load() error {
|
||||
data, err := os.ReadFile(receiver.ConfigFile)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return err
|
||||
}
|
||||
if err := yaml.Unmarshal(data, receiver); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (receiver *ServerConf) Rewrite() error {
|
||||
data, err := yaml.Marshal(receiver)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.WriteFile(receiver.ConfigFile, data, os.ModePerm); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user