How to check whether hostname is domain name in Go?
Asked Answered
P

4

5

How can I check whether URL.Hostname is a valid domain name? I am searching for the exact same behaviour as URI.CheckHostName in the .NET framework.

Punchy answered 13/1, 2018 at 10:47 Comment(1)
Currently, there is no solution using standard library only. You need to use third party library/regex. However, if you need to support internationalized domain name, the task may not trivial. See https://mcmap.net/q/378938/-fully-qualified-domain-name-validation, https://mcmap.net/q/209847/-valid-characters-of-a-hostnameStanislaus
C
5

You could use idna, kind of, to check on this.

import  "golang.org/x/net/idna"
h, err := idna.Lookup.ToASCII("example.com")
fmt.Println(h, err)

Also see;

Coyne answered 7/7, 2022 at 21:3 Comment(1)
Why do you say "kind of"? Would you mind explaining the caveat?Collum
K
3

See my code here.

The function checks if the provided domain name is valid relative to the rules. It doesn't check if the domain name exist.

Kirstinkirstyn answered 29/6, 2018 at 16:7 Comment(0)
L
0

The function IsDNSName from the govalidator package should do what you want. For details on installing it, see the README.

Loaves answered 13/1, 2018 at 11:10 Comment(1)
It allows underscore in domain names which is wrong. See RFC1034 section 3.5. A later change to this RFC is to allow digits as first label character. The TLD label can't start with a digit to avoid confusion between domain names and IPv4 addresses.Kirstinkirstyn
G
0

Here you have. https://pkg.go.dev/github.com/dchest/validator

func ValidateDomainByResolvingIt(domain string) error ValidateDomainByResolvingIt queries DNS for the given domain name, and returns nil if the the name resolves, or an error.

Gritty answered 12/4, 2023 at 11:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.