/
helper.go
78 lines (67 loc) · 2.18 KB
/
helper.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// Copyright 2022 m01i0ng <alley.ma@qq.com>. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file. The original repo for
// this file is https://github.com/m01i0ng/mblog.
package mblog
import (
"os"
"path/filepath"
"strings"
"github.com/m01i0ng/mblog/internal/mblog/store"
"github.com/m01i0ng/mblog/internal/pkg/log"
"github.com/m01i0ng/mblog/pkg/db"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
recommendedHomeDir = ".mblog.sql"
defaultConfigName = "mblog.sql.yaml"
)
func initConfig() {
if cfgFile != "" {
viper.SetConfigFile(cfgFile)
} else {
home, err := os.UserHomeDir()
cobra.CheckErr(err)
viper.AddConfigPath(filepath.Join(home, recommendedHomeDir))
viper.AddConfigPath(".")
viper.SetConfigType("yaml")
viper.SetConfigName(defaultConfigName)
}
viper.AutomaticEnv()
viper.SetEnvPrefix("MBLOG")
replacer := strings.NewReplacer(".", "=")
viper.SetEnvKeyReplacer(replacer)
if err := viper.ReadInConfig(); err != nil {
log.Errorw("Failed to read viper config file", "err", err)
}
log.Infow("Using config file", "file", viper.ConfigFileUsed())
}
func logOptions() *log.Options {
return &log.Options{
DisableCaller: viper.GetBool("log.disable-caller"),
DisableStacktrace: viper.GetBool("log.disable-stacktrace"),
Level: viper.GetString("log.level"),
Format: viper.GetString("log.format"),
OutputPaths: viper.GetStringSlice("log.output-paths"),
}
}
func initStore() error {
opts := &db.MySQLOptions{
Host: viper.GetString("db.host"),
Port: viper.GetInt("db.port"),
Username: viper.GetString("db.username"),
Password: viper.GetString("db.password"),
Database: viper.GetString("db.database"),
MaxIdleConnections: viper.GetInt("db.max-idle-connections"),
MaxOpenConnections: viper.GetInt("db.max-open-connections"),
MaxConnectionLifeTime: viper.GetDuration("db.max-connection-life-time"),
LogLevel: viper.GetInt("db.log-level"),
}
newMySQL, err := db.NewMySQL(opts)
if err != nil {
return err
}
_ = store.NewStore(newMySQL)
return nil
}