Skip to content

Instantly share code, notes, and snippets.

@edr3x
Created May 17, 2024 10:43
Show Gist options
  • Save edr3x/e4f732d4371467515f6a319ec6974932 to your computer and use it in GitHub Desktop.
Save edr3x/e4f732d4371467515f6a319ec6974932 to your computer and use it in GitHub Desktop.
Utility function to check if the domain is valid or not
package main
import (
"fmt"
"regexp"
"golang.org/x/net/publicsuffix"
)
func isRootDomain(domain string) (bool, error) {
publicSuffix, icannManaged := publicsuffix.PublicSuffix(domain)
if !icannManaged {
return false, fmt.Errorf("the domain %s is not ICANN managed", domain)
}
return domain == publicSuffix, nil
}
func isValidSyntax(domain string) bool {
// Regular expression for validating the domain syntax
domainRegex := regexp.MustCompile(`^(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$`)
return domainRegex.MatchString(domain)
}
func isValidDomain(domain string) (bool, error) {
if !isValidSyntax(domain) {
return false, fmt.Errorf("invalid domain syntax")
}
isRoot, err := isRootDomain(domain)
if err != nil {
return false, err
}
if isRoot {
return false, fmt.Errorf("%s is a root domain", domain)
}
return true, nil
}
func main() {
domains := []string{
"example.co.uk",
"test.com",
"c.gaa",
"domainname",
"com",
"com.np",
}
for _, domain := range domains {
valid, err := isValidDomain(domain)
if valid {
fmt.Printf("%s is valid domain.\n", domain)
} else {
fmt.Printf("invalid domain: %s , %v\n", domain, err)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment