-
Notifications
You must be signed in to change notification settings - Fork 249
/
config.go
77 lines (69 loc) · 1.54 KB
/
config.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
package codegen
import (
"github.com/sirupsen/logrus"
"github.com/unionj-cloud/go-doudou/version"
"os"
"path/filepath"
"text/template"
)
var configTmpl = `/**
* Generated by go-doudou {{.Version}}.
* You can edit it as your need.
*/
package config
import (
"github.com/kelseyhightower/envconfig"
"github.com/sirupsen/logrus"
)
type Config struct {
DbConf DbConfig
}
type DbConfig struct {
Driver string ` + "`" + `default:"mysql"` + "`" + `
Host string ` + "`" + `default:"localhost"` + "`" + `
Port string ` + "`" + `default:"3306"` + "`" + `
User string
Passwd string
Schema string
Charset string ` + "`" + `default:"utf8mb4"` + "`" + `
}
func LoadFromEnv() *Config {
var dbconf DbConfig
err := envconfig.Process("db", &dbconf)
if err != nil {
logrus.Panicln("Error processing env", err)
}
return &Config{
dbconf,
}
}
`
//GenConfig generates config file
func GenConfig(dir string) {
var (
err error
configfile string
f *os.File
tpl *template.Template
configDir string
)
configDir = filepath.Join(dir, "config")
if err = os.MkdirAll(configDir, os.ModePerm); err != nil {
panic(err)
}
configfile = filepath.Join(configDir, "config.go")
if _, err = os.Stat(configfile); os.IsNotExist(err) {
if f, err = os.Create(configfile); err != nil {
panic(err)
}
defer f.Close()
tpl, _ = template.New("config.go.tmpl").Parse(configTmpl)
_ = tpl.Execute(f, struct {
Version string
}{
Version: version.Release,
})
} else {
logrus.Warnf("file %s already exists", configfile)
}
}