Go URL解析實例

URL提供了一種統一的方法來定位資源。 以下是在Go中解析網址的方法。這裏將解析此示例URL,其中包括方案,身份驗證信息,主機,端口,路徑,查詢參數和查詢片段。
解析URL並確保沒有錯誤。

可參考示例中的代碼 -

所有的示例代碼,都放在 F:\worksp\golang 目錄下。安裝Go編程環境請參考:http://www.yiibai.com/go/go\_environment.html

url-parsing.go的完整代碼如下所示 -

package main

import "fmt"
import "net"
import "net/url"

func main() {

    // We'll parse this example URL, which includes a
    // scheme, authentication info, host, port, path,
    // query params, and query fragment.
    s := "postgres://user:[email protected]:5432/path?k=v#f"

    // Parse the URL and ensure there are no errors.
    u, err := url.Parse(s)
    if err != nil {
        panic(err)
    }

    // Accessing the scheme is straightforward.
    fmt.Println(u.Scheme)

    // `User` contains all authentication info; call
    // `Username` and `Password` on this for individual
    // values.
    fmt.Println(u.User)
    fmt.Println(u.User.Username())
    p, _ := u.User.Password()
    fmt.Println(p)

    // The `Host` contains both the hostname and the port,
    // if present. Use `SplitHostPort` to extract them.
    fmt.Println(u.Host)
    host, port, _ := net.SplitHostPort(u.Host)
    fmt.Println(host)
    fmt.Println(port)

    // Here we extract the `path` and the fragment after
    // the `#`.
    fmt.Println(u.Path)
    fmt.Println(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(u.RawQuery)
    m, _ := url.ParseQuery(u.RawQuery)
    fmt.Println(m)
    fmt.Println(m["k"][0])
}

執行上面代碼,將得到以下輸出結果 -

F:\worksp\golang>go run url-parsing.go
postgres
user:pass
user
pass
host.com:5432
host.com
5432
/path
f
k=v
map[k:[v]]
v