gmode.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. // Copyright 2019 gf Author(https://github.com/gogf/gf). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. // Package gmode provides release mode management for project.
  7. //
  8. // It uses string to mark the mode instead of integer, which is convenient for configuration.
  9. package gmode
  10. import (
  11. "github.com/gogf/gf/debug/gdebug"
  12. "github.com/gogf/gf/os/gcmd"
  13. "github.com/gogf/gf/os/gfile"
  14. )
  15. const (
  16. NOT_SET = "not-set"
  17. DEVELOP = "develop"
  18. TESTING = "testing"
  19. STAGING = "staging"
  20. PRODUCT = "product"
  21. cmdEnvKey = "gf.gmode"
  22. )
  23. var (
  24. currentMode = NOT_SET
  25. )
  26. // Set sets the mode for current application.
  27. func Set(mode string) {
  28. currentMode = mode
  29. }
  30. // SetDevelop sets current mode DEVELOP for current application.
  31. func SetDevelop() {
  32. Set(DEVELOP)
  33. }
  34. // SetTesting sets current mode TESTING for current application.
  35. func SetTesting() {
  36. Set(TESTING)
  37. }
  38. // SetStaging sets current mode STAGING for current application.
  39. func SetStaging() {
  40. Set(STAGING)
  41. }
  42. // SetProduct sets current mode PRODUCT for current application.
  43. func SetProduct() {
  44. Set(PRODUCT)
  45. }
  46. // Mode returns current application mode set.
  47. func Mode() string {
  48. // If current mode is not set, do this auto check.
  49. if currentMode == NOT_SET {
  50. if v := gcmd.GetWithEnv(cmdEnvKey).String(); v != "" {
  51. // Mode configured from command argument of environment.
  52. currentMode = v
  53. } else {
  54. // If there are source codes found, it's in develop mode, or else in product mode.
  55. if gfile.Exists(gdebug.CallerFilePath()) {
  56. currentMode = DEVELOP
  57. } else {
  58. currentMode = PRODUCT
  59. }
  60. }
  61. }
  62. return currentMode
  63. }
  64. // IsDevelop checks and returns whether current application is running in DEVELOP mode.
  65. func IsDevelop() bool {
  66. return Mode() == DEVELOP
  67. }
  68. // IsTesting checks and returns whether current application is running in TESTING mode.
  69. func IsTesting() bool {
  70. return Mode() == TESTING
  71. }
  72. // IsStaging checks and returns whether current application is running in STAGING mode.
  73. func IsStaging() bool {
  74. return Mode() == STAGING
  75. }
  76. // IsProduct checks and returns whether current application is running in PRODUCT mode.
  77. func IsProduct() bool {
  78. return Mode() == PRODUCT
  79. }