| 68 | |
| 69 | #[tokio::main] |
| 70 | async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { |
| 71 | let cache_dir = tempfile::tempdir().unwrap(); |
| 72 | let cache_manager = |
| 73 | CACacheManager::new(cache_dir.path().to_path_buf(), true); |
| 74 | |
| 75 | // Create HTTP cache |
| 76 | let cache = HttpCache { |
| 77 | mode: CacheMode::Default, |
| 78 | manager: cache_manager, |
| 79 | options: HttpCacheOptions { |
| 80 | cache_status_headers: true, |
| 81 | ..Default::default() |
| 82 | }, |
| 83 | }; |
| 84 | |
| 85 | // Create the cache layer |
| 86 | let cache_layer = HttpCacheLayer::with_cache(cache); |
| 87 | |
| 88 | // Build the service with caching middleware |
| 89 | let mut service = |
| 90 | ServiceBuilder::new().layer(cache_layer).service(MockService::new()); |
| 91 | |
| 92 | println!("Testing HTTP caching with tower/hyper..."); |
| 93 | |
| 94 | // First request |
| 95 | let start = Instant::now(); |
| 96 | let req = Request::builder() |
| 97 | .uri("http://example.com/test") |
| 98 | .body(Full::new(Bytes::new()))?; |
| 99 | let response = service.call(req).await?; |
| 100 | let duration1 = start.elapsed(); |
| 101 | |
| 102 | println!("First request: {:?}", duration1); |
| 103 | println!("Status: {}", response.status().as_u16()); |
| 104 | |
| 105 | // Check cache headers after first request |
| 106 | for (name, value) in response.headers() { |
| 107 | let name_str = name.as_str(); |
| 108 | if name_str.starts_with("x-cache") { |
| 109 | println!("Cache header {}: {}", name, value.to_str().unwrap_or("")); |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | println!(); |
| 114 | |
| 115 | // Second request (should be much faster due to caching) |
| 116 | let start = Instant::now(); |
| 117 | let req = Request::builder() |
| 118 | .uri("http://example.com/test") |
| 119 | .body(Full::new(Bytes::new()))?; |
| 120 | let response = service.call(req).await?; |
| 121 | let duration2 = start.elapsed(); |
| 122 | |
| 123 | println!("Second request: {:?}", duration2); |
| 124 | println!("Status: {}", response.status().as_u16()); |
| 125 | |
| 126 | // Check cache headers after second request |
| 127 | for (name, value) in response.headers() { |