Browse Source

[add] 环境变量方式~

bvbej 2 years ago
parent
commit
78a6a546ca
1 changed files with 14 additions and 11 deletions
  1. 14 11
      pkg/env/env.go

+ 14 - 11
pkg/env/env.go

@@ -1,17 +1,16 @@
 package env
 
 import (
-	"flag"
 	"fmt"
 	"strings"
 )
 
 var (
 	active Environment
-	dev    Environment = &environment{value: "dev"}
-	fat    Environment = &environment{value: "fat"}
-	uat    Environment = &environment{value: "uat"}
-	pro    Environment = &environment{value: "pro"}
+	dev    Environment = &environment{value: "dev"} //开发环境
+	fat    Environment = &environment{value: "fat"} //测试环境
+	uat    Environment = &environment{value: "uat"} //预上线环境
+	pro    Environment = &environment{value: "pro"} //正式环境
 )
 
 var _ Environment = (*environment)(nil)
@@ -52,11 +51,10 @@ func (e *environment) IsPro() bool {
 
 func (e *environment) t() {}
 
-func init() {
-	env := flag.String("env", "", "请输入运行环境:\n dev:开发环境\n fat:测试环境\n uat:预上线环境\n pro:正式环境\n")
-	flag.Parse()
+func Set(env string) error {
+	var err error
 
-	switch strings.ToLower(strings.TrimSpace(*env)) {
+	switch strings.ToLower(strings.TrimSpace(env)) {
 	case "dev":
 		active = dev
 	case "fat":
@@ -66,12 +64,17 @@ func init() {
 	case "pro":
 		active = pro
 	default:
-		active = dev
-		fmt.Println("Warning: '-env' cannot be found, or it is illegal. The default 'dev' will be used.")
+		err = fmt.Errorf("'%s' cannot be found, or it is illegal. enum:dev(开发环境),fat(测试环境),uat(预上线环境),pro(正式环境)", env)
 	}
+
+	return err
 }
 
 // Active 当前配置的env
 func Active() Environment {
+	if active == nil {
+		fmt.Println("Warning: environment not set. The default 'dev' will be used.")
+		active = dev
+	}
 	return active
 }