You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止Rust的Url::parse自动编码并触发错误?

阻止url crate的Url::parse自动编码并触发错误的方法

我正在使用url crate中的Url::parse方法,示例代码如下:

let input = "http://example.com:8080/?sort=custom&kind=comm        <    >   ents&scope=discover&time=6mo&page=2";

match Url::parse(&input) {
    Ok(u) => println!("Url: {}",u),
    Err(err) => println!("Error: {}",err),
}

输入包含空格以及<、>字符,我预期代码会触发Err分支,但Url::parse自动对这些字符进行了百分号编码,输出结果为:

http://example.com:8080/?sort=custom&kind=comm%20%20%20%20%20%20%20%20%3C%20%20%20%20%3E%20%20%20ents&scope=discover&time=6mo&page=2

Url::parse的默认行为符合URL标准,会自动对查询参数中的非法字符进行编码。要阻止这种行为并触发错误,需要手动校验原始输入中是否存在未编码的非法字符,具体实现如下:

  1. 编写字符校验函数,判断字符是否属于URL查询部分允许未编码的范围(参考RFC 3986规范):
fn is_valid_query_char(c: char) -> bool {
    // 允许的未编码字符:字母、数字,以及指定的保留/未保留符号
    c.is_ascii_alphanumeric() 
    || matches!(c, '-' | '_' | '.' | '~' | '!' | '$' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | ';' | '=' | ':' | '/' | '?' | '@')
}
  1. 提取输入中的查询部分,检查是否存在非法字符:
fn has_invalid_unencoded_chars(input: &str) -> bool {
    input.split_once('?')
        .map(|(_, query)| query.chars().any(|c| !is_valid_query_char(c)))
        .unwrap_or(false)
}
  1. 在解析URL前先执行校验,非法字符直接触发错误分支:
let input = "http://example.com:8080/?sort=custom&kind=comm        <    >   ents&scope=discover&time=6mo&page=2";

if has_invalid_unencoded_chars(input) {
    println!("Error: 输入包含未编码的非法字符");
} else {
    match Url::parse(&input) {
        Ok(u) => println!("Url: {}", u),
        Err(err) => println!("Error: {}", err),
    }
}

这样就能在遇到空格、<、>这类未编码的非法字符时,直接触发错误提示,而不会让Url::parse自动编码。

内容的提问来源于stack exchange,提问作者sudoExclamationExclamation

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 23:36:17