Skip to main content

proxyparser/
lib.rs

1// src/lib.rs
2pub mod env_proxy;
3pub mod log;
4pub mod pac;
5pub mod proxy;
6pub mod system_proxy;
7use std::error::Error;
8
9/// Detects the appropriate proxy for the given URL, following standard priority order:
10///
11/// 1. Environment variables (HTTP_PROXY, etc.)
12/// 2. System proxy settings (with full PAC script support on supported platforms)
13/// 3. DIRECT (no proxy)
14///
15/// Supports macOS, Windows, and Linux system settings, including PAC files.
16///
17/// # Examples
18///
19/// ```
20/// use proxyparser::find_proxy_for_url;
21///
22/// let proxy = find_proxy_for_url("https://httpbin.org/ip")?;
23/// println!("{}", proxy); // DIRECT or normalized proxy URL(s)
24/// # Ok::<(), Box<dyn std::error::Error>>(())
25/// ```
26pub fn find_proxy_for_url(url: &str) -> Result<String, Box<dyn Error>> {
27    // 1. 环境变量最高优先级
28    if let Some(proxy) = env_proxy::get_env_proxy(url) {
29        log_info!("Using environment proxy: {}", proxy);
30        return Ok(proxy);
31    }
32
33    // 2. 系统代理(macOS / Windows / Linux)
34    if let Some(system_result) = system_proxy::get_system_proxy_config(url) {
35        match system_result {
36            system_proxy::SystemProxyConfig::PacUrl(pac_url) => {
37                log_info!("Detected PAC configuration: {}", pac_url);
38                match pac::evaluate_pac_for_url(&pac_url, url) {
39                    Ok(proxy) => {
40                        log_info!("PAC resolved proxy: {}", proxy);
41                        return Ok(proxy);
42                    }
43                    Err(e) => {
44                        log_warn!("PAC evaluation failed: {}. Falling back to DIRECT", e);
45                    }
46                }
47            }
48            system_proxy::SystemProxyConfig::Manual(proxy) => {
49                log_info!("Using system manual proxy: {}", proxy);
50                let parsed =
51                    proxy::parse_proxy_result(&proxy, &proxy::ProxyParseOptions::default());
52                return Ok(parsed.to_proxy_string());
53            }
54        }
55    }
56
57    log_info!("No proxy found, using DIRECT");
58    Ok("DIRECT".to_string())
59}