Created
September 7, 2019 03:42
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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