pastebin/config/config.go
2023-09-30 21:47:59 +08:00

65 lines
1.2 KiB
Go

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
}