From 7f2796464f61123a3c36804fdf8431ca2a6d7de6 Mon Sep 17 00:00:00 2001 From: bestgopher <84328409@qq.com> Date: Sat, 18 Apr 2020 16:46:57 +0800 Subject: [PATCH] add `isValidPORTEnvVar` function to judge the environment variable PORT whether is valid --- utils.go | 16 +++++++++++++--- utils_test.go | 15 +++++++++++++++ 2 files changed, 28 insertions(+), 3 deletions(-) diff --git a/utils.go b/utils.go index 71b80de7..bcc9c49d 100644 --- a/utils.go +++ b/utils.go @@ -11,6 +11,7 @@ import ( "path" "reflect" "runtime" + "strconv" "strings" ) @@ -138,10 +139,12 @@ func resolveAddress(addr []string) string { switch len(addr) { case 0: if port := os.Getenv("PORT"); port != "" { - debugPrint("Environment variable PORT=\"%s\"", port) - return ":" + port + if isValidPORTEnvVar(port) { + debugPrint("Environment variable PORT=\"%s\"", port) + return ":" + port + } } - debugPrint("Environment variable PORT is undefined. Using port :8080 by default") + debugPrint("Environment variable PORT is undefined or invalid. Using port :8080 by default") return ":8080" case 1: return addr[0] @@ -149,3 +152,10 @@ func resolveAddress(addr []string) string { panic("too many parameters") } } + +// Determine the PORT environment variable whether is valid。 +// If the PORT can be parsed to uint(0-65535),return true。 +func isValidPORTEnvVar(portString string) bool { + _, err := strconv.ParseUint(portString, 10, 16) + return err == nil +} diff --git a/utils_test.go b/utils_test.go index 9b57c57b..4bf620cb 100644 --- a/utils_test.go +++ b/utils_test.go @@ -137,3 +137,18 @@ func TestMarshalXMLforH(t *testing.T) { e := h.MarshalXML(enc, x) assert.Error(t, e) } + +func TestIsValidPPORTEnvVar(t *testing.T) { + assert.Equal(t, false, isValidPORTEnvVar("abc")) + assert.Equal(t, false, isValidPORTEnvVar("-1")) + assert.Equal(t, false, isValidPORTEnvVar("-100")) + assert.Equal(t, true, isValidPORTEnvVar("1")) + assert.Equal(t, true, isValidPORTEnvVar("1000")) + assert.Equal(t, true, isValidPORTEnvVar("10000")) + assert.Equal(t, false, isValidPORTEnvVar(" 10000")) + assert.Equal(t, false, isValidPORTEnvVar("10000 ")) + assert.Equal(t, false, isValidPORTEnvVar("10000.")) + assert.Equal(t, true, isValidPORTEnvVar("65535")) + assert.Equal(t, false, isValidPORTEnvVar("65536")) + assert.Equal(t, false, isValidPORTEnvVar("655360")) +}