config.go 1.92 KB
Newer Older
hujiebin's avatar
hujiebin committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
package config

import (
	"github.com/joho/godotenv"
	"github.com/sirupsen/logrus"
	"gopkg.in/ini.v1"
	"os"
	"runtime"
	"strconv"
)

func GetMode() string {
	return mode
}

func AppIsRelease() bool {
	return GetMode() == RELEASE
}

hujiebin's avatar
hujiebin committed
20 21 22 23
func AppIsLocal() bool {
	return GetMode() == LOCAL
}

hujiebin's avatar
hujiebin committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
//数据库的配置
type MysqlConfig struct {
	MYSQL_HOST     string
	MYSQL_USERNAME string
	MYSQL_PASSWORD string
	MYSQL_DB       string
}

type MysqlCodeConfig struct {
	MYSQL_HOST     string
	MYSQL_USERNAME string
	MYSQL_PASSWORD string
	MYSQL_DB       string
}

//redis配置
type RedisConfig struct {
hujiebin's avatar
hujiebin committed
41 42 43 44
	REDIS_HOST             string
	REDIS_PASSWORD         string
	REDIS_CLUSTER_HOST     string
	REDIS_CLUSTER_PASSWORD string
hujiebin's avatar
hujiebin committed
45 46 47 48 49 50 51 52 53 54 55 56 57
}

const (
	LOCAL   string = "local"
	DEBUG   string = "debug"
	RELEASE string = "release"
)

var mysqlConfigData MysqlConfig
var redisConfigData RedisConfig
var mode string
var master bool

hujiebin's avatar
hujiebin committed
58 59 60 61 62 63 64 65
func GetConfigMysql() MysqlConfig {
	return mysqlConfigData
}

func GetConfigRedis() RedisConfig {
	return redisConfigData
}

hujiebin's avatar
hujiebin committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
func init() {
	str, _ := os.Getwd()
	logrus.New().Info(str)

	envDir := ".env"

	//加载环境变量
	if err := godotenv.Load(envDir); err != nil {
		logrus.New().Fatalf("Error loading .env err:%v", err)
	}

	//获取环境变量
	mode = os.Getenv("MODE")
	var err error
	master, _ = strconv.ParseBool(os.Getenv("MASTER"))
	logrus.New().Infof("My role is %t", master)

	iniDir := mode + ".ini"
	if runtime.GOOS == "darwin" { // mac本地调试
		iniDir = "/var/log/hilo/" + iniDir
	}
	//根据环境变量获取具体的配置,实现多环境配置
	//var conf *ini.File
	conf, err := ini.LoadSources(ini.LoadOptions{IgnoreInlineComment: true}, iniDir)
	if err != nil {
		logrus.New().Fatal(err)
	}

	//加载mysql的配置
	if err := conf.Section("DATABASE").MapTo(&mysqlConfigData); err != nil {
		logrus.New().Fatal(err)
	}

	if err := conf.Section("REDIS").MapTo(&redisConfigData); err != nil {
		logrus.New().Fatal(err)
	}
}