gmode.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // Copyright GoFrame Author(https://goframe.org). 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. commandEnvKey = "gf.gmode"
  22. )
  23. var (
  24. // Note that `currentMode` is not concurrent safe.
  25. currentMode = NOT_SET
  26. )
  27. // Set sets the mode for current application.
  28. func Set(mode string) {
  29. currentMode = mode
  30. }
  31. // SetDevelop sets current mode DEVELOP for current application.
  32. func SetDevelop() {
  33. Set(DEVELOP)
  34. }
  35. // SetTesting sets current mode TESTING for current application.
  36. func SetTesting() {
  37. Set(TESTING)
  38. }
  39. // SetStaging sets current mode STAGING for current application.
  40. func SetStaging() {
  41. Set(STAGING)
  42. }
  43. // SetProduct sets current mode PRODUCT for current application.
  44. func SetProduct() {
  45. Set(PRODUCT)
  46. }
  47. // Mode returns current application mode set.
  48. func Mode() string {
  49. // If current mode is not set, do this auto check.
  50. if currentMode == NOT_SET {
  51. if v := gcmd.GetOptWithEnv(commandEnvKey).String(); v != "" {
  52. // Mode configured from command argument of environment.
  53. currentMode = v
  54. } else {
  55. // If there are source codes found, it's in develop mode, or else in product mode.
  56. if gfile.Exists(gdebug.CallerFilePath()) {
  57. currentMode = DEVELOP
  58. } else {
  59. currentMode = PRODUCT
  60. }
  61. }
  62. }
  63. return currentMode
  64. }
  65. // IsDevelop checks and returns whether current application is running in DEVELOP mode.
  66. func IsDevelop() bool {
  67. return Mode() == DEVELOP
  68. }
  69. // IsTesting checks and returns whether current application is running in TESTING mode.
  70. func IsTesting() bool {
  71. return Mode() == TESTING
  72. }
  73. // IsStaging checks and returns whether current application is running in STAGING mode.
  74. func IsStaging() bool {
  75. return Mode() == STAGING
  76. }
  77. // IsProduct checks and returns whether current application is running in PRODUCT mode.
  78. func IsProduct() bool {
  79. return Mode() == PRODUCT
  80. }