gin/mode.go

99 lines
2.4 KiB
Go
Raw Permalink Normal View History

// Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2014-08-29 17:49:50 +00:00
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package gin
import (
"flag"
2016-04-15 08:12:07 +00:00
"io"
"os"
"sync/atomic"
2015-04-07 16:37:17 +00:00
"github.com/gin-gonic/gin/binding"
)
// EnvGinMode indicates environment name for gin mode.
const EnvGinMode = "GIN_MODE"
const (
// DebugMode indicates gin mode is debug.
DebugMode = "debug"
2018-11-12 10:58:24 +00:00
// ReleaseMode indicates gin mode is release.
ReleaseMode = "release"
// TestMode indicates gin mode is test.
TestMode = "test"
)
const (
2017-03-11 13:35:29 +00:00
debugCode = iota
releaseCode
testCode
)
// DefaultWriter is the default io.Writer used by Gin for debug output and
// middleware output like Logger() or Recovery().
// Note that both Logger and Recovery provides custom ways to configure their
// output io.Writer.
// To support coloring in Windows use:
//
// import "github.com/mattn/go-colorable"
// gin.DefaultWriter = colorable.NewColorableStdout()
2016-04-15 08:12:07 +00:00
var DefaultWriter io.Writer = os.Stdout
// DefaultErrorWriter is the default io.Writer used by Gin to debug errors
2016-04-15 08:12:07 +00:00
var DefaultErrorWriter io.Writer = os.Stderr
var ginMode int32 = debugCode
var modeName atomic.Value
2014-10-08 23:40:42 +00:00
func init() {
mode := os.Getenv(EnvGinMode)
SetMode(mode)
2014-10-08 23:40:42 +00:00
}
// SetMode sets gin mode according to input string.
func SetMode(value string) {
2020-04-16 14:31:58 +00:00
if value == "" {
if flag.Lookup("test.v") != nil {
value = TestMode
} else {
value = DebugMode
}
2020-04-16 14:31:58 +00:00
}
switch value {
case DebugMode, "":
atomic.StoreInt32(&ginMode, debugCode)
case ReleaseMode:
atomic.StoreInt32(&ginMode, releaseCode)
2014-08-20 23:01:05 +00:00
case TestMode:
atomic.StoreInt32(&ginMode, testCode)
default:
panic("gin mode unknown: " + value + " (available mode: debug release test)")
}
modeName.Store(value)
}
// DisableBindValidation closes the default validator.
func DisableBindValidation() {
binding.Validator = nil
}
// EnableJsonDecoderUseNumber sets true for binding.EnableDecoderUseNumber to
// call the UseNumber method on the JSON Decoder instance.
func EnableJsonDecoderUseNumber() {
binding.EnableDecoderUseNumber = true
}
// EnableJsonDecoderDisallowUnknownFields sets true for binding.EnableDecoderDisallowUnknownFields to
// call the DisallowUnknownFields method on the JSON Decoder instance.
func EnableJsonDecoderDisallowUnknownFields() {
binding.EnableDecoderDisallowUnknownFields = true
}
2021-12-15 15:27:23 +00:00
// Mode returns current gin mode.
func Mode() string {
return modeName.Load().(string)
}