add `isValidPORTEnvVar` function to judge the environment variable PORT whether is valid

This commit is contained in:
bestgopher 2020-04-18 16:46:57 +08:00
parent 90fff292d7
commit 7f2796464f
2 changed files with 28 additions and 3 deletions

View File

@ -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
}

View File

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