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")) +}