Skip to main content

create_proxy

Function create_proxy 

Source
pub fn create_proxy(config: CreateProxyConfig) -> (Router, RefreshTrigger)
Expand description

The main library interface for using phantom-frame as a library Returns a proxy handler function and a refresh trigger

Examples found in repository?
examples/library_usage.rs (line 30)
7async fn main() {
8    // Initialize tracing (optional but recommended)
9    // tracing_subscriber::fmt::init();
10
11    // Create proxy configuration
12    // You can specify method prefixes to filter by HTTP method
13    let proxy_config = CreateProxyConfig::new("http://localhost:8080".to_string())
14        .with_include_paths(vec![
15            "/api/*".to_string(),
16            "/public/*".to_string(),
17            "GET /admin/stats".to_string(), // Only cache GET requests to this endpoint
18        ])
19        .with_exclude_paths(vec![
20            "/api/admin/*".to_string(),
21            "POST *".to_string(),   // Don't cache any POST requests
22            "PUT *".to_string(),    // Don't cache any PUT requests
23            "DELETE *".to_string(), // Don't cache any DELETE requests
24        ])
25        .caching_strategy(CacheStrategy::None)
26        .compression_strategy(CompressStrategy::Brotli)
27        .with_websocket_enabled(true); // Enable WebSocket support (default: true)
28
29    // Create proxy - proxy_url is the backend server to proxy requests to
30    let (proxy_app, refresh_trigger): (Router, RefreshTrigger) = create_proxy(proxy_config);
31
32    // You can clone and use the refresh_trigger in your code
33    let trigger_clone = refresh_trigger.clone();
34
35    // Example: Trigger cache refresh from another part of your application
36    tokio::spawn(async move {
37        tokio::time::sleep(tokio::time::Duration::from_secs(60)).await;
38
39        // Clear all cache entries
40        trigger_clone.trigger();
41        println!("All cache cleared!");
42
43        tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
44
45        // Clear only cache entries matching a pattern (supports wildcards)
46        trigger_clone.trigger_by_key_match("GET:/api/*");
47        println!("Cache cleared for GET:/api/* pattern!");
48    });
49
50    // Start the proxy server
51    let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
52
53    println!("Proxy server listening on http://0.0.0.0:3000");
54    println!("Caching paths: /api/*, /public/*, GET /admin/stats");
55    println!("Excluding: /api/admin/*, POST *, PUT *, DELETE *");
56    println!("Cache strategy: none (proxy-only mode)");
57    println!("Compression strategy: brotli (applies only to cached responses)");
58    println!("Note: Cache reads and writes are disabled in this example");
59    println!("WebSocket support: enabled");
60
61    axum::serve(listener, proxy_app).await.unwrap();
62}