Extract Subdomain From Request In Go

Here’s a code snippet that extracts the subdomain from an user’s request and places it as the first element in a new array.

R represents http.Request, and subdomain represents a new string array that has the extracted subdomain as its first and only element.

//The Host that the user queried.
host := r.URL.Host
host = strings.TrimSpace(host)
//Figure out if a subdomain exists in the host given.
host_parts := strings.Split(host, ".")
if len(host_parts) > 2 {
    //The subdomain exists, we store it as the first element 
    //in a new array
    subdomain := []string{host_parts[0]}
}