mode.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "flag"
  7. "io"
  8. "os"
  9. "github.com/gin-gonic/gin/binding"
  10. )
  11. // EnvGinMode indicates environment name for gin mode.
  12. const EnvGinMode = "GIN_MODE"
  13. const (
  14. // DebugMode indicates gin mode is debug.
  15. DebugMode = "debug"
  16. // ReleaseMode indicates gin mode is release.
  17. ReleaseMode = "release"
  18. // TestMode indicates gin mode is test.
  19. TestMode = "test"
  20. )
  21. const (
  22. debugCode = iota
  23. releaseCode
  24. testCode
  25. )
  26. // DefaultWriter is the default io.Writer used by Gin for debug output and
  27. // middleware output like Logger() or Recovery().
  28. // Note that both Logger and Recovery provides custom ways to configure their
  29. // output io.Writer.
  30. // To support coloring in Windows use:
  31. //
  32. // import "github.com/mattn/go-colorable"
  33. // gin.DefaultWriter = colorable.NewColorableStdout()
  34. var DefaultWriter io.Writer = os.Stdout
  35. // DefaultErrorWriter is the default io.Writer used by Gin to debug errors
  36. var DefaultErrorWriter io.Writer = os.Stderr
  37. var (
  38. ginMode = debugCode
  39. modeName = DebugMode
  40. )
  41. func init() {
  42. mode := os.Getenv(EnvGinMode)
  43. SetMode(mode)
  44. }
  45. // SetMode sets gin mode according to input string.
  46. func SetMode(value string) {
  47. if value == "" {
  48. if flag.Lookup("test.v") != nil {
  49. value = TestMode
  50. } else {
  51. value = DebugMode
  52. }
  53. }
  54. switch value {
  55. case DebugMode:
  56. ginMode = debugCode
  57. case ReleaseMode:
  58. ginMode = releaseCode
  59. case TestMode:
  60. ginMode = testCode
  61. default:
  62. panic("gin mode unknown: " + value + " (available mode: debug release test)")
  63. }
  64. modeName = value
  65. }
  66. // DisableBindValidation closes the default validator.
  67. func DisableBindValidation() {
  68. binding.Validator = nil
  69. }
  70. // EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to
  71. // call the UseNumber method on the JSON Decoder instance.
  72. func EnableJsonDecoderUseNumber() {
  73. binding.EnableDecoderUseNumber = true
  74. }
  75. // EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to
  76. // call the DisallowUnknownFields method on the JSON Decoder instance.
  77. func EnableJsonDecoderDisallowUnknownFields() {
  78. binding.EnableDecoderDisallowUnknownFields = true
  79. }
  80. // Mode returns current gin mode.
  81. func Mode() string {
  82. return modeName
  83. }