How to specify string type/format in golang

hello, i’m creating a program which takes hostname as input from the user. as you know hostname is in format of server.hostname.com
so i want that if hostname is invalid then it will exit.
like if customer entered 1 or hello or domain.com or example.com then it will exit, and if customer entered correct hostname like server.server.com , vps.mydomain.com etc. then it will print correct.

any idea about it??

Valid after what exact condition? hello looks like a correct hostname for me… As well as example.com

1 Like

It’s unclear to me what you mean by “valid”. I think you might be confused about what a hostname is. In your example, it looks like maybe you want “contains subdomain, second-level domain, and top level domain”. In general, I believe net/url is what you’re after. The following:

package main

import (
	"fmt"
	"log"
	"net/url"
	"strings"
)

func main() {
	testCases := []string{"server.hostname.com", "server.hostname.com:443/?q=asdf", "1", "hello", "domain.com", "123.asd.xyz", "has space in it"}
	for _, h := range testCases {
		validateHost(h)
		validateSubdomain(h)
	}
}

func validateHost(hn string) {
	u := parseURI(hn)
	if len(u.Host) > 0 {
		// Try changing this to u.Hostname() to strip port number...
		fmt.Println(u.Host, "is a valid host name")
	}
}

func validateSubdomain(hn string) {
	u := parseURI(hn)
	if strings.Count(u.Host, ".") == 2 {
		fmt.Println(u.Host, "contains sub, second-level, and top level domain")
	}
}

func parseURI(hn string) *url.URL {
	// hard-code scheme to https
	u, err := url.Parse("https://" + hn)
	if err != nil {
		log.Fatal(err)
	}
	return u
}

https://play.golang.org/p/y0Hr43XteiN

… will get you:

server.hostname.com is a valid host name
server.hostname.com contains sub, second-level, and top level domain
server.hostname.com:443 is a valid host name
server.hostname.com:443 contains sub, second-level, and top level domain
1 is a valid host name
hello is a valid host name
domain.com is a valid host name
123.asd.xyz is a valid host name
123.asd.xyz contains sub, second-level, and top level domain
2009/11/10 23:00:00 parse "https://has space in it": invalid character " " in host name

… which should be enough to hopefully get you started.

1 Like