mode.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  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. // import "github.com/mattn/go-colorable"
  32. // gin.DefaultWriter = colorable.NewColorableStdout()
  33. var DefaultWriter io.Writer = os.Stdout
  34. // DefaultErrorWriter is the default io.Writer used by Gin to debug errors
  35. var DefaultErrorWriter io.Writer = os.Stderr
  36. var (
  37. ginMode = debugCode
  38. modeName = DebugMode
  39. )
  40. func init() {
  41. mode := os.Getenv(EnvGinMode)
  42. SetMode(mode)
  43. }
  44. // SetMode sets gin mode according to input string.
  45. func SetMode(value string) {
  46. if value == "" {
  47. if flag.Lookup("test.v") != nil {
  48. value = TestMode
  49. } else {
  50. value = DebugMode
  51. }
  52. }
  53. switch value {
  54. case DebugMode:
  55. ginMode = debugCode
  56. case ReleaseMode:
  57. ginMode = releaseCode
  58. case TestMode:
  59. ginMode = testCode
  60. default:
  61. panic("gin mode unknown: " + value + " (available mode: debug release test)")
  62. }
  63. modeName = value
  64. }
  65. // DisableBindValidation closes the default validator.
  66. func DisableBindValidation() {
  67. binding.Validator = nil
  68. }
  69. // EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to
  70. // call the UseNumber method on the JSON Decoder instance.
  71. func EnableJsonDecoderUseNumber() {
  72. binding.EnableDecoderUseNumber = true
  73. }
  74. // EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to
  75. // call the DisallowUnknownFields method on the JSON Decoder instance.
  76. func EnableJsonDecoderDisallowUnknownFields() {
  77. binding.EnableDecoderDisallowUnknownFields = true
  78. }
  79. // Mode returns current gin mode.
  80. func Mode() string {
  81. return modeName
  82. }