Go基础 专题
专题目录
您的位置:go > Go基础 专题 > Go URL解析实例
Go URL解析实例
作者:--    发布时间:2019-11-20

url提供了一种统一的方法来定位资源。 以下是在go中解析网址的方法。这里将解析此示例url,其中包括方案,身份验证信息,主机,端口,路径,查询参数和查询片段。
解析url并确保没有错误。

可参考示例中的代码 -

所有的示例代码,都放在 f:\worksp\golang 目录下。安装go编程环境请参考:http://www.h3.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:pass@host.com: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

网站声明:
本站部分内容来自网络,如您发现本站内容
侵害到您的利益,请联系本站管理员处理。
联系站长
373515719@qq.com
关于本站:
编程参考手册