url parsing

This commit is contained in:
badkaktus 2019-10-11 10:40:17 +03:00
parent d982b0a724
commit 908f8dc36e
3 changed files with 20 additions and 22 deletions

View File

@ -52,7 +52,7 @@ Epoch
Форматирование времени (Time Formatting / Parsing)
Случайные числа (Random Numbers)
Парсинг чисел (Number Parsing)
URL Parsing
Парсинг URL (URL Parsing)
SHA1 Hashes
Base64 Encoding
Reading Files

View File

@ -1,5 +1,5 @@
// URLs provide a [uniform way to locate resources](https://adam.herokuapp.com/past/2010/3/30/urls_are_the_uniform_way_to_locate_resources/).
// Here's how to parse URLs in Go.
// URL - это [уникальный локатор ресурса](https://adam.herokuapp.com/past/2010/3/30/urls_are_the_uniform_way_to_locate_resources/).
// Рассмотрим как парсить URL в Go.
package main
@ -11,45 +11,43 @@ import (
func main() {
// We'll parse this example URL, which includes a
// scheme, authentication info, host, port, path,
// query params, and query fragment.
// Мы будем разбирать этот URL, который содержит схему,
// аутентификационные данные, хост, порт, путь, параметры
// и фрагмент запроса.
s := "postgres://user:pass@host.com:5432/path?k=v#f"
// Parse the URL and ensure there are no errors.
// Парсим URL и убеждаемся, что нет ошибок.
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.
// `User` содержит всю аутентификационную информацию; используйте
// `Username` и `Password` если надо получить конкретное поле.
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.
// `Host` содержит поля хост и порт, если они определены.
// Воспользуйтесь `SplitHostPort`, чтобы разделить их.
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.
// Для получения параметров в строке вида `k=v`
// используйте `RawQuery`. Вы так же можете разобрать
// запрос в карту. Разобранный запрос в карту из строк
// превращается в срез строк, так первый элемент будет
// находиться по адресу `[0]`.
fmt.Println(u.RawQuery)
m, _ := url.ParseQuery(u.RawQuery)
fmt.Println(m)

View File

@ -1,5 +1,5 @@
# Running our URL parsing program shows all the different
# pieces that we extracted.
# Запуск нашей программы парсинга URL показывает все
# различные фрагменты, которые мы извлекли.
$ go run url-parsing.go
postgres
user:pass