63 lines
1.2 KiB
Go
63 lines
1.2 KiB
Go
package template
|
|
|
|
const templateConfig = `package config
|
|
|
|
import (
|
|
"os"
|
|
|
|
"github.com/sirupsen/logrus"
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type ServerConfig struct {
|
|
ServerName string ` + "`" + `yaml:"server-name"` + "`" + `
|
|
ServerListen string ` + "`" + `yaml:"server-listen"` + "`" + `
|
|
GrpcListen string ` + "`" + `yaml:"grpc-listen"` + "`" + `
|
|
Environment string ` + "`" + `yaml:"environment"` + "`" + `
|
|
}
|
|
|
|
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
|
|
}
|
|
`
|