Fragment Description:

Parsing urls.
URLs provide a [uniform way to locate resources] URL stands for Uniform Resource Locator.
Decoding a URL is a uniform (standard) way to locate any resource (service) over a network.
Any time you wish to locate a resource on the internet, use a URL.
Here's how to parse URLs in Go (a lot of vocabulary!).


Last update, on 2015, Fri 9 Oct, 16:15:38

/* ... <== see fragment description ... */

package main

import (

func main() {
    // We'll parse this example URL, which includes a
    // scheme, authentication info, host, port, path,
    // query params, and query fragment.
    s := "postgres://"
    fmt.Println("URL parsed as u:\t\t", s, "\n")
    // fmt.Println("URL to parse == ", s, "\n")
    // Parse the URL and ensure there are no errors.
    u, err := url.Parse(s)
    if err != nil {
    // Accessing the scheme is straightforward.
    fmt.Println("Scheme:\t\t\t", u.Scheme)
    // "User" contains all authentication info; call
    // "Username" and "Password" on this for individual
    // values.
    fmt.Println("User is:\t\t\t", u.User)
    fmt.Println("User.Username:\t\t", u.User.Username())
    p, _ := u.User.Password()
    fmt.Println("User.Password:\t\t", p)
    // The "Host" contains both the hostname and the port,
    // if present. "Split" the "Host" manually to extract
    // the port.
    fmt.Println("Host:\t\t\t", u.Host)
    h := strings.Split(u.Host, ":")
    fmt.Printf("Host.domainName:\t\t%s\n", h[0])
    fmt.Printf("Host.port:\t\t%s\n", h[1])
    // Here we extract the "path" and the fragment after
    // the "#".
    fmt.Println("Path:\t\t\t", u.Path[1:])
    fmt.Println("Fragment:\t\t\t", u.Fragment)
    // To get query params in a string of "k=v" format,
    // use "RawQuery". You can also parse query params
    // into a map. The parsed query param maps are from
    // strings to slices of strings, so index into "[0]"
    // if you only want the first value.
    fmt.Println("RawQuery:\t\t\t", u.RawQuery)
    m, _ := url.ParseQuery(u.RawQuery)
    fmt.Println("url.ParseQuery(u.RawQuery):\t", m)
    fmt.Println("m[\"k\"][0] is:\t\t", m["k"][0])

/* Expected Output:
URL parsed as u:        postgres://
Scheme:             postgres
User is:            user:pass
User.Username:      user
User.Password:      pass
Host.port:     5432
Path:           Path1/Path2
Fragment:           f
RawQuery:           k=v
url.ParseQuery(u.RawQuery):     map[k:[v]]
m["k"][0] is:         v