judge whether the environment variable PORT is valid

This commit is contained in:
bestgopher 2020-04-16 23:15:37 +08:00
parent a4e947a356
commit bbf546d5cf
2 changed files with 20 additions and 1 deletions

View File

@ -11,6 +11,7 @@ import (
"path" "path"
"reflect" "reflect"
"runtime" "runtime"
"strconv"
"strings" "strings"
) )
@ -137,7 +138,7 @@ func joinPaths(absolutePath, relativePath string) string {
func resolveAddress(addr []string) string { func resolveAddress(addr []string) string {
switch len(addr) { switch len(addr) {
case 0: case 0:
if port := os.Getenv("PORT"); port != "" { if port := os.Getenv("PORT"); port != "" && isValidPortEnvVar(port) {
debugPrint("Environment variable PORT=\"%s\"", port) debugPrint("Environment variable PORT=\"%s\"", port)
return ":" + port return ":" + port
} }
@ -149,3 +150,10 @@ func resolveAddress(addr []string) string {
panic("too many parameters") panic("too many parameters")
} }
} }
// Determine whether the PORT environment variable is valid。
// If the PORT can be parsed to int(0-65535)return true。
func isValidPortEnvVar(portString string) bool {
_, err := strconv.ParseUint(portString, 10, 16)
return err == nil
}

View File

@ -137,3 +137,14 @@ func TestMarshalXMLforH(t *testing.T) {
e := h.MarshalXML(enc, x) e := h.MarshalXML(enc, x)
assert.Error(t, e) assert.Error(t, e)
} }
func TestIsValidPortEnvVar(t *testing.T) {
assert.Equal(t, false, isValidPortEnvVar("abc"))
assert.Equal(t, false, isValidPortEnvVar("-1"))
assert.Equal(t, true, isValidPortEnvVar("1"))
assert.Equal(t, true, isValidPortEnvVar("1000"))
assert.Equal(t, true, isValidPortEnvVar("10000"))
assert.Equal(t, true, isValidPortEnvVar("65535"))
assert.Equal(t, false, isValidPortEnvVar("65536"))
assert.Equal(t, false, isValidPortEnvVar("655360"))
}