Skip to content

Instantly share code, notes, and snippets.

@bmcculley
Created September 7, 2019 03:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmcculley/1cdd354b5aac95eb1558ffd704165325 to your computer and use it in GitHub Desktop.
Save bmcculley/1cdd354b5aac95eb1558ffd704165325 to your computer and use it in GitHub Desktop.
Parse a hostname into a slice from a URL https://play.golang.com/p/et2gNy1MgjD
package main
import (
"fmt"
"log"
"net/url"
"strings"
)
func ParseHostname(domain string) []string {
u, err := url.Parse(domain)
if err != nil {
log.Fatal(err)
}
hostname := u.Hostname()
hostname_slice := strings.Split(hostname, ".")
return hostname_slice
}
func main() {
parts := ParseHostname("http://subdomain.example.com:3000")
fmt.Println(parts)
}
package main
import (
"reflect"
"testing"
)
func TestParseHostname(t *testing.T) {
t.Run("test subdomain.example.com", func(t *testing.T) {
got := ParseHostname("http://subdomain.example.com")
want := []string{"subdomain", "example", "com"}
if !reflect.DeepEqual(got, want) {
t.Errorf("got %v want %v", got, want)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment