github.com/unionj-cloud/go-doudou@v1.3.8-0.20221011095552-0088008e5b31/cmd/internal/svc/codegen/config.go (about) 1 package codegen 2 3 import ( 4 "github.com/sirupsen/logrus" 5 "github.com/unionj-cloud/go-doudou/version" 6 "os" 7 "path/filepath" 8 "text/template" 9 ) 10 11 var configTmpl = `/** 12 * Generated by go-doudou {{.Version}}. 13 * You can edit it as your need. 14 */ 15 package config 16 17 import ( 18 "github.com/kelseyhightower/envconfig" 19 "github.com/unionj-cloud/go-doudou/toolkit/zlogger" 20 ) 21 22 type Config struct { 23 DbConf DbConfig 24 } 25 26 type DbConfig struct { 27 Driver string ` + "`" + `default:"mysql"` + "`" + ` 28 Host string ` + "`" + `default:"localhost"` + "`" + ` 29 Port string ` + "`" + `default:"3306"` + "`" + ` 30 User string 31 Passwd string 32 Schema string 33 Charset string ` + "`" + `default:"utf8mb4"` + "`" + ` 34 } 35 36 func LoadFromEnv() *Config { 37 var dbconf DbConfig 38 err := envconfig.Process("db", &dbconf) 39 if err != nil { 40 zlogger.Panic().Err(err).Msg("Error processing env") 41 } 42 return &Config{ 43 dbconf, 44 } 45 } 46 ` 47 48 //GenConfig generates config file 49 func GenConfig(dir string) { 50 var ( 51 err error 52 configfile string 53 f *os.File 54 tpl *template.Template 55 configDir string 56 ) 57 configDir = filepath.Join(dir, "config") 58 if err = os.MkdirAll(configDir, os.ModePerm); err != nil { 59 panic(err) 60 } 61 62 configfile = filepath.Join(configDir, "config.go") 63 if _, err = os.Stat(configfile); os.IsNotExist(err) { 64 if f, err = os.Create(configfile); err != nil { 65 panic(err) 66 } 67 defer f.Close() 68 tpl, _ = template.New("config.go.tmpl").Parse(configTmpl) 69 _ = tpl.Execute(f, struct { 70 Version string 71 }{ 72 Version: version.Release, 73 }) 74 } else { 75 logrus.Warnf("file %s already exists", configfile) 76 } 77 }