From dd32d8de748c017926e3572c792d6cf31bd809f1 Mon Sep 17 00:00:00 2001 From: tom whiston Date: Tue, 20 Mar 2018 00:28:59 +0000 Subject: [PATCH] fix port : prefix issues when building config data --- util/config.go | 45 ++++++++++++++++++++++++++++++--------------- util/config_test.go | 28 ++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 15 deletions(-) create mode 100644 util/config_test.go diff --git a/util/config.go b/util/config.go index b80efe5d..faf85197 100644 --- a/util/config.go +++ b/util/config.go @@ -12,6 +12,7 @@ import ( "github.com/gorilla/securecookie" "golang.org/x/crypto/bcrypt" + "strings" ) var Cookie *securecookie.SecureCookie @@ -134,21 +135,7 @@ func ConfigInit() { } loadConfig() - - if len(os.Getenv("PORT")) > 0 { - Config.Port = ":" + os.Getenv("PORT") - } - if len(Config.Port) == 0 { - Config.Port = ":3000" - } - - if len(Config.TmpPath) == 0 { - Config.TmpPath = "/tmp/semaphore" - } - - if Config.MaxParallelTasks < 1 { - Config.MaxParallelTasks = 10 - } + validateConfig() var encryption []byte encryption = nil @@ -196,6 +183,34 @@ func loadConfig(){ } +func validateConfig(){ + + validatePort() + + if len(Config.TmpPath) == 0 { + Config.TmpPath = "/tmp/semaphore" + } + + if Config.MaxParallelTasks < 1 { + Config.MaxParallelTasks = 10 + } +} + +func validatePort() { + + //TODO - why do we do this only with this variable? + if len(os.Getenv("PORT")) > 0 { + Config.Port = ":" + os.Getenv("PORT") + } + if len(Config.Port) == 0 { + Config.Port = ":3000" + } + if !strings.HasPrefix(Config.Port, ":"){ + Config.Port = ":"+Config.Port + } +} + + func decodeConfig(file *os.File){ if err := json.NewDecoder(file).Decode(&Config); err != nil { diff --git a/util/config_test.go b/util/config_test.go new file mode 100644 index 00000000..ce857840 --- /dev/null +++ b/util/config_test.go @@ -0,0 +1,28 @@ +package util + +import ( + "testing" + "os" +) + +func TestValidatePort(t *testing.T){ + + Config = new(configType) + Config.Port = "" + validatePort() + if Config.Port != ":3000" { + t.Error("no port should get set to default") + } + + Config.Port = "4000" + validatePort() + if Config.Port != ":4000" { + t.Error("Port without : suffix should have it added") + } + + os.Setenv("PORT", "5000") + validatePort() + if Config.Port != ":5000" { + t.Error("Port value should be overwritten by env var, and it should be prefixed appropriately") + } +} \ No newline at end of file