env.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package env
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. var (
  7. active Environment
  8. dev Environment = &environment{value: "dev"} //开发环境
  9. fat Environment = &environment{value: "fat"} //测试环境
  10. uat Environment = &environment{value: "uat"} //预上线环境
  11. pro Environment = &environment{value: "pro"} //正式环境
  12. )
  13. var _ Environment = (*environment)(nil)
  14. // Environment 环境配置
  15. type Environment interface {
  16. Value() string
  17. IsDev() bool
  18. IsFat() bool
  19. IsUat() bool
  20. IsPro() bool
  21. t()
  22. }
  23. type environment struct {
  24. value string
  25. }
  26. func (e *environment) Value() string {
  27. return e.value
  28. }
  29. func (e *environment) IsDev() bool {
  30. return e.value == "dev"
  31. }
  32. func (e *environment) IsFat() bool {
  33. return e.value == "fat"
  34. }
  35. func (e *environment) IsUat() bool {
  36. return e.value == "uat"
  37. }
  38. func (e *environment) IsPro() bool {
  39. return e.value == "pro"
  40. }
  41. func (e *environment) t() {}
  42. func Set(env string) error {
  43. var err error
  44. switch strings.ToLower(strings.TrimSpace(env)) {
  45. case "dev":
  46. active = dev
  47. case "fat":
  48. active = fat
  49. case "uat":
  50. active = uat
  51. case "pro":
  52. active = pro
  53. default:
  54. err = fmt.Errorf("'%s' cannot be found, or it is illegal. enum:dev(开发环境),fat(测试环境),uat(预上线环境),pro(正式环境)", env)
  55. }
  56. return err
  57. }
  58. // Active 当前配置的env
  59. func Active() Environment {
  60. if active == nil {
  61. fmt.Println("Warning: environment not set. The default 'dev' will be used.")
  62. active = dev
  63. }
  64. return active
  65. }