ruk·si

Go
URLs

Updated at 2014-01-20 08:55

Go net/url package offers ways to parse URLs.

package main

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

func main() {
    urlStr := "scheme://username:p4ss@host.com:5432/path/to?label=doris#id-1"
    u, errParseUrl := url.Parse(urlStr)
    if errParseUrl != nil {
        panic(errParseUrl)
    }

    // Host related information.
    fmt.Println(u.Scheme) // => scheme
    fmt.Println(u.Host) // => host.com:5432
    h := strings.Split(u.Host, ":")
    fmt.Println(h[0]) // => host.com
    fmt.Println(h[1]) // => 5432

    // Authentication information.
    fmt.Println(u.User) // => username:p4ss
    fmt.Println(u.User.Username()) // => username
    password, wasSet := u.User.Password()
    fmt.Println(password, wasSet) // => p4ss true

    // Resource location information.
    fmt.Println(u.Path) // => /path/to/resource
    fmt.Println(u.Fragment) // => id-1

    // Additional parameters.
    fmt.Println(u.RawQuery) // => label=doris
    query, errParseQuery := url.ParseQuery(u.RawQuery)
    if errParseQuery != nil {
        panic(errParseQuery)
    }
    fmt.Println(query) // => map[label:[doris]]
    if labels, ok := query["label"]; ok {
        fmt.Println(labels[0]) // => doris
    }
}

Source