URL Parsing {.en}

URL解析 {.zh}

::: {.en} URLs provide a uniform way to locate resources. Here’s how to parse URLs in Go. :::

::: {.zh}

URL提供[查找资源的统一方式](https://adam.herokuapp.com/past/2010/3/30/urls_are_the_uniform_way_to_locate_resources/)。这是如何解析Go中的URL。

:::

  1. package main
  2. import "fmt"
  3. import "net"
  4. import "net/url"
  5. func main() {

::: {.en} We’ll parse this example URL, which includes a scheme, authentication info, host, port, path, query params, and query fragment. :::

::: {.zh}

我们将解析此示例URL,其中包括ascheme,身份验证信息,主机,端口,路径,查询参数和查询片段。

:::

  1. s := "postgres://user:pass@host.com:5432/path?k=v#f"

::: {.en} Parse the URL and ensure there are no errors. :::

::: {.zh}

解析URL并确保没有错误。

:::

  1. u, err := url.Parse(s)
  2. if err != nil {
  3. panic(err)
  4. }

::: {.en} Accessing the scheme is straightforward. :::

::: {.zh}

访问该方案很简单。

:::

  1. fmt.Println(u.Scheme)

::: {.en} User contains all authentication info; call Username and Password on this for individual values. :::

::: {.zh}

User包含所有身份验证信息;为个别值调用usernamePassword

:::

  1. fmt.Println(u.User)
  2. fmt.Println(u.User.Username())
  3. p, _ := u.User.Password()
  4. fmt.Println(p)

::: {.en} The Host contains both the hostname and the port, if present. Use SplitHostPort to extract them. :::

::: {.zh}

Host包含主机名和端口(如果存在)。使用SplitHostPort来提取它们。

:::

  1. fmt.Println(u.Host)
  2. host, port, _ := net.SplitHostPort(u.Host)
  3. fmt.Println(host)
  4. fmt.Println(port)

::: {.en} Here we extract the path and the fragment after the #. :::

::: {.zh}

在这里,我们在后面提取path和片段。

:::

  1. fmt.Println(u.Path)
  2. fmt.Println(u.Fragment)

::: {.en} 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. :::

::: {.zh}

要以k = v格式的字符串获取查询参数,请使用RawQuery。您还可以将查询paramsin解析为地图。解析后的查询参数映射是从字符串到字符串切片,因此如果只需要第一个值,则索引到“[0]`。

:::

  1. fmt.Println(u.RawQuery)
  2. m, _ := url.ParseQuery(u.RawQuery)
  3. fmt.Println(m)
  4. fmt.Println(m["k"][0])
  5. }

::: {.en} Running our URL parsing program shows all the different pieces that we extracted. :::

::: {.zh}

运行我们的URL解析程序会显示我们提取的所有不同的部分。

:::

  1. $ go run url-parsing.go
  2. postgres
  3. user:pass
  4. user
  5. pass
  6. host.com:5432
  7. host.com
  8. 5432
  9. /path
  10. f
  11. k=v
  12. map[k:[v]]
  13. v