Add mode constant

This commit is contained in:
Jannis Mattheis 2018-03-15 21:36:07 +01:00 committed by Jannis Mattheis
parent 41259f3f77
commit 488cffc87b
2 changed files with 78 additions and 0 deletions

43
mode/mode.go Normal file
View File

@ -0,0 +1,43 @@
package mode
import "github.com/gin-gonic/gin"
const (
// Dev for development mode
Dev = "dev"
// Prod for production mode
Prod = "prod"
// TestDev used for tests
TestDev = "testdev"
)
var mode = Dev;
// Set sets the new mode.
func Set(newMode string) {
mode = newMode;
updateGinMode()
}
// Get returns the current mode.
func Get() string {
return mode;
}
// IsDev returns true if the current mode is dev mode.
func IsDev() bool {
return Get() == Dev || Get() == TestDev;
}
func updateGinMode() {
switch Get() {
case Dev:
gin.SetMode(gin.DebugMode)
case TestDev:
gin.SetMode(gin.TestMode)
case Prod:
gin.SetMode(gin.ReleaseMode)
default:
panic("unknown mode")
}
}

35
mode/mode_test.go Normal file
View File

@ -0,0 +1,35 @@
package mode
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/gin-gonic/gin"
)
func TestDevMode(t *testing.T) {
Set(Dev)
assert.Equal(t, Get(), Dev)
assert.True(t, IsDev())
assert.Equal(t, gin.Mode(), gin.DebugMode)
}
func TestTestDevMode(t *testing.T) {
Set(TestDev)
assert.Equal(t, Get(), TestDev)
assert.True(t, IsDev())
assert.Equal(t, gin.Mode(), gin.TestMode)
}
func TestProdMode(t *testing.T) {
Set(Prod)
assert.Equal(t, Get(), Prod)
assert.False(t, IsDev())
assert.Equal(t, gin.Mode(), gin.ReleaseMode)
}
func TestInvalidMode(t *testing.T) {
assert.Panics(t, func() {
Set("asdasda")
})
}