85 lines
1.7 KiB
Go
Raw Normal View History

2024-03-31 20:09:20 +08:00
package opt
import (
"encoding/json"
"flag"
"github.com/sirupsen/logrus"
"io"
"os"
"path"
"runtime"
"strconv"
)
type database struct {
Type string `json:"type"` // postgresql, mysql, sqlite
Path string `json:"path"`
Host string `json:"host"`
Port int `json:"port"`
DB string `json:"db"`
Username string `json:"username"`
Password string `json:"password"`
}
type cache struct {
Type string `json:"type"` // redis, memor
Host string `json:"host"`
Port int `json:"port"`
Username string `json:"username"`
Password string `json:"password"`
}
type config struct {
Name string `json:"name"`
Address string `json:"address"`
Database database `json:"database"`
Cache cache `json:"cache"`
}
var (
ConfigFile string
Debug int
Cfg = &config{}
)
func MustInitConfig() {
flag.Parse()
var (
err error
cf *os.File
bs []byte
)
if cf, err = os.Open(ConfigFile); err != nil {
logrus.Panicf("MustInitConfig: open config file=%s err=%v", ConfigFile, err)
}
defer cf.Close()
if bs, err = io.ReadAll(cf); err != nil {
logrus.Panicf("MustInitConfig: read in config file err=%v", err)
}
if err = json.Unmarshal(bs, Cfg); err != nil {
logrus.Panicf("MustInitConfig: json marshal config=%s err=%v", string(bs), err)
}
if Debug > 0 {
logrus.SetLevel(logrus.DebugLevel)
if Debug >= 9999 {
logrus.SetLevel(logrus.TraceLevel)
logrus.SetReportCaller(true)
logrus.SetFormatter(&logrus.TextFormatter{
ForceColors: true,
CallerPrettyfier: func(frame *runtime.Frame) (string, string) {
file := path.Base(frame.File)
return "", " " + file + ":" + strconv.Itoa(frame.Line)
},
})
}
}
logrus.Infof("read in config detail: \n%s", string(bs))
}