Перейти к содержимому
Топаз6.0 · До релиза
Загрузка →

Поиск в документации

Спецификация 6.0

Выберите результат стрелками и нажмите Enter, чтобы открыть его.

Введите имя API, номер диагностики, правило или тему проекта.

    Библиотека · std.url

    URL.query

    Returns an independent map of form-decoded query names and ordered value arrays.

    query() -> Map<string, Array<string>>
    Модуль
    std.url →
    Получатель
    URL
    Минимальное число аргументов
    0
    Максимальное число аргументов
    0

    Declaration and parameters

    Ссылка

    Доступность

    Включено по умолчанию · Не определено

    Import std.url in language mode 5.21.

    The current compiler selects std/url.tpz for this language mode. Availability in other released editions and inclusion in each installed distribution are Pending.

    Получатель

    URL

    Ограничения параметров

    URL.query returns a new Map from decoded names to arrays of decoded values. A missing query and an empty query both produce an empty map.

    Query decoding follows application/x-www-form-urlencoded parsing. Ampersands separate fields. Empty fields between separators are skipped. The first equals sign separates each name from its value. A field without that sign has an empty value.

    An explicit empty name is retained. A plus sign decodes to an ASCII space. Valid percent escapes decode to bytes and those bytes decode as UTF-8. Malformed percent escapes remain literal text and invalid UTF-8 sequences use the replacement character.

    Repeated names are grouped after decoding. Values retain encounter order. Map keys retain the order in which their decoded names first appear. No sorting, deduplication, or comma splitting occurs.

    The returned Map and its value arrays follow collection value semantics. URL.toString preserves the stored serialized query rather than serializing this map.

    Reading a query evaluates its receiver once and performs no external operation. A constructed URL can always produce its query map. Query decoding does not return a diagnostic or a Result error.

    Результат

    The declared result type is Map<string, Array<string>>.

    Эффекты

    Ошибки

    Result and effects

    Ссылка

    Returns an independent map of form-decoded query names and ordered value arrays.

    Resolved contracts

    Ссылка

    Related entries

    Ссылка

    std.url →

    Decode query fields into an independent map

    Ссылка
    Правилоtopaz.stdlib.contract.url-query.rule

    Decode query fields into an independent map

    URL.query returns a new Map from decoded names to arrays of decoded values. A missing query and an empty query both produce an empty map.

    Query decoding follows application/x-www-form-urlencoded parsing. Ampersands separate fields. Empty fields between separators are skipped. The first equals sign separates each name from its value. A field without that sign has an empty value.

    An explicit empty name is retained. A plus sign decodes to an ASCII space. Valid percent escapes decode to bytes and those bytes decode as UTF-8. Malformed percent escapes remain literal text and invalid UTF-8 sequences use the replacement character.

    Repeated names are grouped after decoding. Values retain encounter order. Map keys retain the order in which their decoded names first appear. No sorting, deduplication, or comma splitting occurs.

    The returned Map and its value arrays follow collection value semantics. URL.toString preserves the stored serialized query rather than serializing this map.

    Reading a query evaluates its receiver once and performs no external operation. A constructed URL can always produce its query map. Query decoding does not return a diagnostic or a Result error.

    Причина

    Query syntax has its own escaping rules and permits repeated names. Grouped arrays preserve every value while immutable URLs keep query inspection from silently rewriting a link.

    Decode repeated query fields and preserve their value order

    Ссылка
    main.tpzDecode repeated query fields and preserve their value orderОткрыть песочницу →
    1. import std.url { URL }
    2. import std.io
    3. match (URL.parse("https://example.com/?q=a+b&q=%ED%95%9C&empty&x=a=b&=blank")) {
    4. case Ok(value) => {
    5. let fields = value.query()
    6. for name in (["q", "empty", "x", ""]) {
    7. match (fields.get(name)) {
    8. case Some(values) => {
    9. for item in (values) {
    10. io.writeLine("{name}={item}")
    11. }
    12. }
    13. case None() => io.writeLine("missing")
    14. }
    15. }
    16. }
    17. case Err(_) => io.writeLine("parse failed")
    18. }
    Ожидаемый выводКод завершения 0
    q=a b
    q=한
    empty=
    x=a=b
    =blank
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. q=a b
    2. q=한
    3. empty=
    4. x=a=b
    5. =blank

    Skip empty separators while retaining an explicit empty field

    Ссылка
    main.tpzSkip empty separators while retaining an explicit empty fieldОткрыть песочницу →
    1. import std.url { URL }
    2. import std.io
    3. for text in (["https://example.com/", "https://example.com/?", "https://example.com/?&&a=1&&", "https://example.com/?="]) {
    4. match (URL.parse(text)) {
    5. case Ok(value) => {
    6. let fields = value.query()
    7. let hasEmptyName = fields.containsKey("")
    8. io.writeLine("{fields.length}:{hasEmptyName}")
    9. }
    10. case Err(_) => io.writeLine("parse failed")
    11. }
    12. }
    Ожидаемый выводКод завершения 0
    0:false
    0:false
    1:false
    1:true
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 0:false
    2. 0:false
    3. 1:false
    4. 1:true

    Keep malformed percent escapes as query data

    Ссылка
    main.tpzKeep malformed percent escapes as query dataОткрыть песочницу →
    1. import std.url { URL }
    2. import std.io
    3. for text in (["https://example.com/?x=%", "https://example.com/?x=%GG"]) {
    4. match (URL.parse(text)) {
    5. case Ok(value) => {
    6. match (value.query().get("x")) {
    7. case Some(values) => io.writeLine(values[0])
    8. case None() => io.writeLine("missing")
    9. }
    10. }
    11. case Err(_) => io.writeLine("parse failed")
    12. }
    13. }
    Ожидаемый выводКод завершения 0
    %
    %GG
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. %
    2. %GG

    Replace an invalid decoded UTF-8 byte in a query field

    Ссылка
    main.tpzReplace an invalid decoded UTF-8 byte in a query fieldОткрыть песочницу →
    1. import std.url { URL }
    2. import std.io
    3. match (URL.parse("https://example.com/?x=%ff")) {
    4. case Ok(value) => {
    5. match (value.query().get("x")) {
    6. case Some(values) => io.writeLine(values[0])
    7. case None() => io.writeLine("missing")
    8. }
    9. io.writeLine(value.toString())
    10. }
    11. case Err(_) => io.writeLine("parse failed")
    12. }
    Ожидаемый выводКод завершения 0
    �
    https://example.com/?x=%ff
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. �
    2. https://example.com/?x=%ff

    Mutate a query snapshot without changing its URL

    Ссылка
    main.tpzMutate a query snapshot without changing its URLОткрыть песочницу →
    1. import std.url { URL }
    2. import std.io
    3. match (URL.parse("https://example.com/?k=first")) {
    4. case Ok(value) => {
    5. let mut snapshot = value.query()
    6. snapshot.insert("k", ["changed", "again"])
    7. snapshot.insert("extra", ["local"])
    8. let reread = value.query()
    9. io.writeLine("{reread.length}")
    10. match (reread.get("k")) {
    11. case Some(values) => {
    12. for item in (values) {
    13. io.writeLine(item)
    14. }
    15. }
    16. case None() => io.writeLine("missing")
    17. }
    18. io.writeLine(value.toString())
    19. }
    20. case Err(_) => io.writeLine("parse failed")
    21. }
    Ожидаемый выводКод завершения 0
    1
    first
    https://example.com/?k=first
    
    $ topaz run main.tpz · Целевой продукт 5.21.3
    Ожидаемый результат

    Ожидаемый результат

    Выполнение завершается. Код завершения 0.

    Ожидаемый стандартный вывод
    1. 1
    2. first
    3. https://example.com/?k=first

    Меню

    Загрузка →