filer/controller/config.go

73 lines
1.4 KiB
Go

package controller
import (
"fmt"
"os"
"runtime"
"gopkg.in/yaml.v3"
)
func getHomeProfile() string {
if runtime.GOOS == "windows" {
return os.Getenv("USERPROFILE") + "\\.filer"
}
return os.Getenv("HOME") + "/.filer"
}
func init() {
NewConfig(getHomeProfile())
}
type ServerConfig struct {
ConfigFile string `yaml:"-"`
Environment string `yaml:"environment" json:"environment"`
Upyun UpyunConfig `yaml:"upyun" json:"upyun"`
}
type UpyunConfig struct {
Bucket string `yaml:"bucket" json:"bucket"`
Operator string `yaml:"operator" json:"operator"`
Password string `yaml:"password" json:"password"`
Domain string `yaml:"domain" json:"domain"`
}
var conf *ServerConfig
func NewConfig(fileName string) {
conf = new(ServerConfig)
conf.ConfigFile = fileName
if err := conf.Load(); err != nil {
panic(err)
}
}
func GetConfig() *ServerConfig {
if conf == nil {
panic(fmt.Errorf("config not init"))
}
return conf
}
func (receiver *ServerConfig) 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 *ServerConfig) 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
}