nezha/model/config.go

65 lines
1.1 KiB
Go
Raw Normal View History

2019-12-08 03:59:58 -05:00
package model
import (
2019-12-20 10:58:09 -05:00
"fmt"
2020-12-09 06:05:40 -05:00
"io/ioutil"
"os"
2019-12-20 10:58:09 -05:00
2019-12-08 03:59:58 -05:00
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
2020-12-09 06:05:40 -05:00
"gopkg.in/yaml.v2"
2019-12-08 03:59:58 -05:00
)
type Config struct {
Debug bool
Site struct {
Brand string // 站点名称
CookieName string // 浏览器 Cookie 名称
2020-12-09 06:05:40 -05:00
Theme string
2020-12-23 20:54:17 -05:00
CustomCode string
2019-12-08 03:59:58 -05:00
}
GitHub struct {
2020-11-29 09:17:40 -05:00
Admin string // 管理员ID列表
2019-12-08 03:59:58 -05:00
ClientID string
ClientSecret string
}
HTTPPort uint
EnableIPChangeNotification bool
2019-12-20 10:58:09 -05:00
v *viper.Viper
2019-12-08 03:59:58 -05:00
}
2019-12-20 10:58:09 -05:00
func (c *Config) Read(path string) error {
c.v = viper.New()
c.v.SetConfigFile(path)
err := c.v.ReadInConfig()
2019-12-08 03:59:58 -05:00
if err != nil {
2019-12-20 10:58:09 -05:00
return err
2019-12-08 03:59:58 -05:00
}
2019-12-20 10:58:09 -05:00
err = c.v.Unmarshal(c)
2019-12-08 03:59:58 -05:00
if err != nil {
2019-12-20 10:58:09 -05:00
return err
2019-12-08 03:59:58 -05:00
}
2020-12-09 06:05:40 -05:00
if c.Site.Theme == "" {
c.Site.Theme = "default"
}
2019-12-20 10:58:09 -05:00
c.v.OnConfigChange(func(in fsnotify.Event) {
c.v.Unmarshal(c)
2020-12-09 06:05:40 -05:00
fmt.Println("配置文件更新,重载配置", c)
2019-12-08 03:59:58 -05:00
})
2019-12-20 10:58:09 -05:00
go c.v.WatchConfig()
return nil
2019-12-08 03:59:58 -05:00
}
2020-12-09 06:05:40 -05:00
func (c *Config) Save() error {
data, err := yaml.Marshal(c)
if err != nil {
return err
}
return ioutil.WriteFile(c.v.ConfigFileUsed(), data, os.ModePerm)
}