You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

26 lines
694 B
Go

package utils
import (
"strings"
"github.com/pkg/errors"
)
// SplitHost returns hostname into domain and subdomain strings.
// For example:
// "some.subdomain.example.com" → ("some.subdomain", "example.com", nil)
// "example.com" → ("", "example.com", nil)
func SplitHost(host string) (subdomain string, domain string, err error) {
subdomains := strings.Split(host, ".")
if len(subdomains) >= 3 {
domain = strings.Join(subdomains[len(subdomains)-2:], ".")
subdomain = strings.Join(subdomains[:len(subdomains)-2], ".")
} else if len(subdomains) == 2 {
domain = strings.Join(subdomains, ".")
} else {
err = errors.New("invalid domain")
}
return subdomain, domain, err
}