Golang : Validate hostname
Problem :
You need to validate if a given string is a valid hostname or not. Hostnames such as :
www.socketloop.com
socketloop.com
google.com
digitalocean.com
Solution :
Use regexp.Compile
function to validate the string.
For example :
package main
import (
"fmt"
"regexp"
"strings"
)
func validHost(host string) bool {
host = strings.Trim(host, " ")
re, _ := regexp.Compile(`^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$`)
if re.MatchString(host) {
return true
}
return false
}
func main() {
host1 := "socketloop.com"
vHost := validHost(host1)
fmt.Printf("%s is a valid hostname : %v \n", host1, vHost)
host2 := "socketloop_com"
vHost2 := validHost(host2)
fmt.Printf("%s is a valid hostname : %v \n", host2, vHost2)
host3 := "socketloop/com"
vHost3 := validHost(host3)
fmt.Printf("%s is a valid hostname : %v \n", host3, vHost3)
host4 := "www.socketloop.com"
vHost4 := validHost(host4)
fmt.Printf("%s is a valid hostname : %v \n", host4, vHost4)
}
Output :
socketloop.com is a valid hostname : true
socketloop_com is a valid hostname : false
socketloop/com is a valid hostname : false
www.socketloop.com is a valid hostname : true
See also : Golang : Validate IP address
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+13.7k Golang : convert rune to unicode hexadecimal value and back to rune character
+17.3k How to enable MariaDB/MySQL logs ?
+29k Golang : JQuery AJAX post data to server and send data back to client example
+7.9k Golang : Reverse text lines or flip line order example
+7.6k Golang : How to feed or take banana with Gorilla Web Toolkit Session package
+7k Golang : How to detect if a sentence ends with a punctuation?
+13.7k Golang : Reverse IP address for reverse DNS lookup example
+22.4k Golang : untar or extract tar ball archive example
+22.2k Generate checksum for a file in Go
+5.3k Unix/Linux : How to find out the hard disk size?
+32.7k Delete a directory in Go
+7.3k Golang : Rename part of filename