add the IP sanitize method

This commit is contained in:
2023-12-29 12:13:20 +03:00
parent e1fea2d149
commit d40c0c6362
3 changed files with 56 additions and 8 deletions
+19 -3
View File
@@ -1,11 +1,18 @@
package sanitize
// Integer returns only numbers
import (
"net"
"regexp"
)
var reIP = regexp.MustCompile(`[^a-zA-Z0-9:.]`) // IPv4 and IPv6 characters only
// Integer returns numbers only
func Integer(input string) string {
runes := []rune{}
n := 0
for _, r := range input {
if !(r == 45) && !(r >= 48 && r <= 57) { // regexp.MustCompile(`[^-\d]`).ReplaceAllString(input, "$1")
if !(r == 45) && !(r >= 48 && r <= 57) { // Ignore any invalid characters first
continue
}
switch r {
@@ -30,7 +37,7 @@ func Float(input string) string {
dot := false
n := 0
for i, r := range input {
if !(r >= 44 && r <= 46) && !(r >= 48 && r <= 57) { // regexp.MustCompile(`[^-\.,\d]`).ReplaceAllString(input, "$1")
if !(r >= 44 && r <= 46) && !(r >= 48 && r <= 57) { // Ignore any invalid characters first
continue
}
switch r {
@@ -58,3 +65,12 @@ func Float(input string) string {
}
return ""
}
// IP returns the IP address in IPv4 or IPv6 format
func IP(input string) string {
sanitized := reIP.ReplaceAllString(input, "")
if ip := net.ParseIP(sanitized); ip != nil {
return ip.String()
}
return ""
}