Skip to content

Commit

Permalink
支持启动时命令行指定配置文件位置和名称,去除viper中的cmd参数绑定
Browse files Browse the repository at this point in the history
  • Loading branch information
axiaoxin committed Dec 10, 2019
1 parent 84f2440 commit 1544c74
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 36 deletions.
14 changes: 13 additions & 1 deletion app/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"context"
"flag"
"log"
"net/http"
"os"
Expand All @@ -15,16 +16,27 @@ import (
"github.com/spf13/viper"
)

const (
// DefaultServerBind 默认运行地址
DefaultServerBind = "localhost:4869"
)

func main() {
log.Println("[INFO] ============ pink-lady ============")
workdir, err := os.Getwd()
if err != nil {
log.Fatal("[FATAL] ", err)
}
app := router.SetupRouter(workdir, "config")
configpath := flag.String("configpath", workdir, "path of config file")
configname := flag.String("configname", "config", "name of config file (no suffix)")
flag.Parse()
app := router.SetupRouter(*configpath, *configname)
apis.RegisterRoutes(app)

bind := viper.GetString("server.bind")
if bind == "" {
bind = DefaultServerBind
}
srv := &http.Server{
Addr: bind,
Handler: app,
Expand Down
17 changes: 16 additions & 1 deletion app/middleware/basicauth.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,24 @@ import (
"github.com/spf13/viper"
)

const (
// DefaultAPIDocsUsername apidocs 默认用户名
DefaultAPIDocsUsername = "admin"
// DefaultAPIDocsPassword apidocs 默认密码
DefaultAPIDocsPassword = "!admin"
)

// BasicAuth use username and password in config to auth
func BasicAuth() gin.HandlerFunc {
username := viper.GetString("apidocs.basicauth.username")
if username == "" {
username = DefaultAPIDocsUsername
}
password := viper.GetString("apidocs.basicauth.password")
if password == "" {
password = DefaultAPIDocsPassword
}
return gin.BasicAuth(gin.Accounts{
viper.GetString("apidocs.basicauth.username"): viper.GetString("apidocs.basicauth.password"),
username: password,
})
}
28 changes: 14 additions & 14 deletions app/router/router.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,18 +19,14 @@ import (
"github.com/gin-gonic/gin"
)

const (
// DefaultPprofPath 默认pprof url
DefaultPprofPath = "/x/debug/pprof"
)

// InitDependencies 初始化所有依赖
func InitDependencies(configPath, configName string) {
bindOpt := utils.NewViperOption("server.bind", "localhost:4869", "server binding address")
modeOpt := utils.NewViperOption("server.mode", "debug", "server mode")
basicAuthUsernameOpt := utils.NewViperOption("apidocs.basicauth.username", "admin", "apidocs default login username")
basicAuthPasswordOpt := utils.NewViperOption("apidocs.basicauth.password", "!admin", "apidocs default login password")
pprofPathOpt := utils.NewViperOption("pprof.path", "/x/debug/pprof", "pprof default register path")
if err := utils.InitViper(configPath, configName, "",
bindOpt, modeOpt,
basicAuthUsernameOpt, basicAuthPasswordOpt,
pprofPathOpt,
); err != nil {
func InitDependencies(configpath, configname string) {
if err := utils.InitViper(configpath, configname, ""); err != nil {
log.Println("[ERROR]", err)
}

Expand All @@ -49,9 +45,9 @@ func InitDependencies(configPath, configName string) {
}

// SetupRouter init and return a gin router
func SetupRouter(configPath, configName string) *gin.Engine {
func SetupRouter(configpath, configname string) *gin.Engine {
// Init
InitDependencies(configPath, configName)
InitDependencies(configpath, configname)

// setup gin
mode := strings.ToLower(viper.GetString("server.mode"))
Expand Down Expand Up @@ -79,7 +75,11 @@ func SetupRouter(configPath, configName string) *gin.Engine {
}

if viper.GetBool("pprof.open") {
pprof.Register(router, viper.GetString("pprof.path"))
pprofPath := viper.GetString("pprof.path")
if pprofPath == "" {
pprofPath = DefaultPprofPath
}
pprof.Register(router, pprofPath)
}

return router
Expand Down
24 changes: 4 additions & 20 deletions app/utils/viper.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (

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

Expand All @@ -28,7 +27,7 @@ func NewViperOption(name string, defaultValue interface{}, desc string) ViperOpt

// InitViper init viper by default value, ENV, cmd flag and config file
// you can use switch to reload server when config file changed
func InitViper(configPath, configName string, envPrefix string, options ...ViperOption) error {
func InitViper(configpath, configname string, envPrefix string, options ...ViperOption) error {
viper.SetEnvPrefix(envPrefix)
for _, option := range options {
// set default value
Expand All @@ -37,31 +36,16 @@ func InitViper(configPath, configName string, envPrefix string, options ...Viper
// bind ENV
viper.BindEnv(option.Name)
viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))

// cmd
if pflag.Lookup(option.Name) == nil {
switch option.Default.(type) {
case int:
pflag.Int(option.Name, option.Default.(int), option.Desc)
case string:
pflag.String(option.Name, option.Default.(string), option.Desc)
case bool:
pflag.Bool(option.Name, option.Default.(bool), option.Desc)
}
}
}

pflag.Parse()
viper.BindPFlags(pflag.CommandLine)

// load conf file
viper.SetConfigName(configName)
viper.AddConfigPath(configPath)
viper.SetConfigName(configname)
viper.AddConfigPath(configpath)
err := viper.ReadInConfig()
if err != nil {
return errors.Wrap(err, "viper read in config error")
}
log.Printf("[INFO] loaded %s in %s\n", configName, configPath)
log.Printf("[INFO] loaded %s in %s\n", configname, configpath)
viper.WatchConfig()
viper.OnConfigChange(func(e fsnotify.Event) {
viper.ReadInConfig()
Expand Down

0 comments on commit 1544c74

Please sign in to comment.