Skip to content

Commit

Permalink
chore: optimize config
Browse files Browse the repository at this point in the history
  • Loading branch information
qloog committed Mar 8, 2021
1 parent 6f7d463 commit 2a9ee5a
Show file tree
Hide file tree
Showing 29 changed files with 191 additions and 133 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -43,5 +43,5 @@ vendor

# custom
snake
conf/config.yaml
conf/config.local.yaml
config/config.yaml
config/config.local.yaml
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

## v1.3.1
- 优化 新建项目命令 `snake new`
- 优化目录结构

## v1.3.0
- 新增 Web 路由、控制器及模板
Expand Down
6 changes: 3 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ RUN go mod download

# 将代码复制到容器中
COPY . .
COPY conf /app/conf
COPY config /app/conf

# Build the Go app
RUN go build -ldflags="-s -w" -o /app/snake .
Expand All @@ -38,13 +38,13 @@ WORKDIR /app

# 从builder镜像中把 /app 拷贝到当前目录
COPY --from=builder /app/snake /app/snake
COPY --from=builder /app/conf /app/conf
COPY --from=builder /app/config /app/conf

# Expose port 8080 to the outside world
EXPOSE 8080

# 需要运行的命令
CMD ["/app/snake", "-c", "conf/config.local.yaml"]
CMD ["/app/snake", "-c", "config/config.local.yaml"]

# 1. build image: docker build -t snake:v1 -f Dockerfile .
# 2. start: docker run --rm -it -p 8080:8080 snake:v1
Expand Down
8 changes: 4 additions & 4 deletions app/web/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ package web
import (
"net/http"

"github.com/spf13/viper"
"github.com/1024casts/snake/config"

"github.com/1024casts/snake/pkg/conf"
"github.com/spf13/viper"

"github.com/1024casts/snake/pkg/errno"
"github.com/1024casts/snake/pkg/flash"
Expand Down Expand Up @@ -51,7 +51,7 @@ func SetLoginCookie(ctx *gin.Context, userID uint64) {

session := GetCookieSession(ctx)
session.Options = &sessions.Options{
Domain: conf.Conf.Cookie.Domain,
Domain: config.Conf.Cookie.Domain,
MaxAge: 86400,
Path: "/",
HttpOnly: true,
Expand All @@ -75,7 +75,7 @@ func SetLoginCookie(ctx *gin.Context, userID uint64) {

// GetCookieSession get cookie
func GetCookieSession(ctx *gin.Context) *sessions.Session {
session, err := Store.Get(ctx.Request, conf.Conf.Cookie.Name)
session, err := Store.Get(ctx.Request, config.Conf.Cookie.Name)
if err != nil {
log.Warnf("[handler] store get err, %v", err)
}
Expand Down
5 changes: 3 additions & 2 deletions app/web/user/logout.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ package user
import (
"net/http"

"github.com/1024casts/snake/config"

"github.com/gin-gonic/gin"
"github.com/gorilla/sessions"

"github.com/1024casts/snake/app/web"
"github.com/1024casts/snake/pkg/conf"
"github.com/1024casts/snake/pkg/log"
)

Expand All @@ -16,7 +17,7 @@ func Logout(c *gin.Context) {
// 删除cookie信息
session := web.GetCookieSession(c)
session.Options = &sessions.Options{
Domain: conf.Conf.Cookie.Domain,
Domain: config.Conf.Cookie.Domain,
Path: "/",
MaxAge: -1,
}
Expand Down
File renamed without changes.
88 changes: 48 additions & 40 deletions pkg/conf/conf.go → config/config.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
package conf
package config

import (
"fmt"
"log"
"strings"
"time"

"github.com/fsnotify/fsnotify"
"github.com/pkg/errors"
"github.com/spf13/viper"

"github.com/1024casts/snake/pkg/log"
"github.com/1024casts/snake/pkg/database/orm"
logger "github.com/1024casts/snake/pkg/log"
)

var (
Expand All @@ -18,47 +20,65 @@ var (
)

// Init init config
func Init(confPath string) error {
err := initConfig(confPath)
func Init(configPath string) (*Config, error) {
cfgFile, err := LoadConfig(configPath)
if err != nil {
return err
log.Fatalf("LoadConfig: %v", err)
}
return nil
cfg, err := ParseConfig(cfgFile)
if err != nil {
log.Fatalf("ParseConfig: %v", err)
}

watchConfig(cfgFile)

Conf = cfg

return cfg, nil
}

// initConfig init config from conf file
func initConfig(confPath string) error {
// LoadConfig load config file from given path
func LoadConfig(confPath string) (*viper.Viper, error) {
v := viper.New()
if confPath != "" {
viper.SetConfigFile(confPath) // 如果指定了配置文件,则解析指定的配置文件
v.SetConfigFile(confPath) // 如果指定了配置文件,则解析指定的配置文件
} else {
viper.AddConfigPath("conf") // 如果没有指定配置文件,则解析默认的配置文件
viper.SetConfigName("config.local")
v.AddConfigPath("config") // 如果没有指定配置文件,则解析默认的配置文件
v.SetConfigName("config.local")
}
viper.SetConfigType("yaml") // 设置配置文件格式为YAML
viper.AutomaticEnv() // 读取匹配的环境变量
v.SetConfigType("yaml") // 设置配置文件格式为YAML
v.AutomaticEnv() // 读取匹配的环境变量
viper.SetEnvPrefix("snake") // 读取环境变量的前缀为 snake
replacer := strings.NewReplacer(".", "_")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil { // viper解析配置文件
return errors.WithStack(err)
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
return nil, errors.New("config file not found")
}
return nil, err
}

// parse to config struct
err := viper.Unmarshal(&Conf)
return v, nil
}

// Parse config file
func ParseConfig(v *viper.Viper) (*Config, error) {
var c Config

err := v.Unmarshal(&c)
if err != nil {
return err
log.Printf("unable to decode into struct, %v", err)
return nil, err
}

watchConfig()

return nil
return &c, nil
}

// 监控配置文件变化并热加载程序
func watchConfig() {
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
log.Infof("Config file changed: %s", e.Name)
func watchConfig(v *viper.Viper) {
v.WatchConfig()
v.OnConfigChange(func(e fsnotify.Event) {
log.Printf("Config file changed: %s", e.Name)
})
}

Expand All @@ -68,7 +88,7 @@ type Config struct {
// common
App AppConfig
Log LogConfig
MySQL MySQLConfig
MySQL orm.Config
Redis RedisConfig
Cache CacheConfig
Email EmailConfig
Expand Down Expand Up @@ -104,18 +124,6 @@ type LogConfig struct {
LogBackupCount uint `mapstructure:"log_backup_count"`
}

// MySQLConfig mysql config
type MySQLConfig struct {
Name string `mapstructure:"name"`
Addr string `mapstructure:"addr"`
UserName string `mapstructure:"username"`
Password string `mapstructure:"password"`
ShowLog bool `mapstructure:"show_log"`
MaxIdleConn int `mapstructure:"max_idle_conn"`
MaxOpenConn int `mapstructure:"max_open_conn"`
ConnMaxLifeTime time.Duration `mapstructure:"conn_max_life_time"`
}

// RedisConfig redis config
type RedisConfig struct {
Addr string `mapstructure:"addr"`
Expand Down Expand Up @@ -174,7 +182,7 @@ type QiNiuConfig struct {
// InitLog init log
func InitLog(cfg *Config) {
c := cfg.Log
config := log.Config{
config := logger.Config{
Name: c.Name,
Writers: c.Writers,
LoggerLevel: c.LoggerLevel,
Expand All @@ -187,7 +195,7 @@ func InitLog(cfg *Config) {
LogRotateSize: c.LogRotateSize,
LogBackupCount: c.LogBackupCount,
}
err := log.NewLogger(&config, log.InstanceZapLogger)
err := logger.NewLogger(&config, logger.InstanceZapLogger)
if err != nil {
fmt.Printf("InitWithConfig err: %v", err)
}
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ require (
github.com/gin-contrib/pprof v1.3.0
github.com/gin-contrib/static v0.0.0-20200916080430-d45d9a37d28e
github.com/gin-gonic/gin v1.6.3
github.com/go-git/go-git/v5 v5.2.0 // indirect
github.com/go-mail/mail v2.3.1+incompatible
github.com/go-playground/validator/v10 v10.2.0
github.com/go-redis/redis v6.15.8+incompatible
Expand Down
Loading

0 comments on commit 2a9ee5a

Please sign in to comment.