mirror of https://github.com/gin-gonic/gin.git
add `isValidPORTEnvVar` function to judge the environment variable PORT whether is valid
This commit is contained in:
parent
90fff292d7
commit
7f2796464f
12
utils.go
12
utils.go
|
@ -11,6 +11,7 @@ import (
|
||||||
"path"
|
"path"
|
||||||
"reflect"
|
"reflect"
|
||||||
"runtime"
|
"runtime"
|
||||||
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
@ -138,10 +139,12 @@ 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 != "" {
|
||||||
|
if isValidPORTEnvVar(port) {
|
||||||
debugPrint("Environment variable PORT=\"%s\"", port)
|
debugPrint("Environment variable PORT=\"%s\"", port)
|
||||||
return ":" + 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"
|
return ":8080"
|
||||||
case 1:
|
case 1:
|
||||||
return addr[0]
|
return addr[0]
|
||||||
|
@ -149,3 +152,10 @@ func resolveAddress(addr []string) string {
|
||||||
panic("too many parameters")
|
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
|
||||||
|
}
|
||||||
|
|
|
@ -137,3 +137,18 @@ func TestMarshalXMLforH(t *testing.T) {
|
||||||
e := h.MarshalXML(enc, x)
|
e := h.MarshalXML(enc, x)
|
||||||
assert.Error(t, e)
|
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"))
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue