httpcan 0.8.1

A simple HTTP Request & Response Service, with httpbin compatibility
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
use super::*;
use actix_web::{body::SizedStream, web::Bytes, HttpResponseBuilder};
use rand::rngs::StdRng;
use rand::{RngExt, SeedableRng};
use std::time::Duration;
use tokio::time::sleep;

#[derive(Deserialize)]
pub struct DripQuery {
    duration: Option<f64>,
    numbytes: Option<usize>,
    code: Option<u16>,
    delay: Option<f64>,
    chunked: Option<bool>,
}

#[derive(Deserialize)]
pub struct BytesQuery {
    seed: Option<u64>,
}

#[derive(Deserialize)]
pub struct StreamBytesQuery {
    seed: Option<u64>,
    chunk_size: Option<usize>,
}

#[derive(Deserialize)]
pub struct RangeQuery {
    chunk_size: Option<usize>,
    duration: Option<f64>,
}

// Helper function to parse Range header - mimics httpbin's __parse_request_range
fn parse_request_range(range_header_value: &str) -> (Option<usize>, Option<usize>) {
    if !range_header_value.starts_with("bytes=") {
        return (None, None);
    }

    let range_part = &range_header_value[6..];

    // Handle multiple ranges (take first one like httpbin)
    let first_range = range_part.split(',').next().unwrap_or(range_part);

    if let Some((start_str, end_str)) = first_range.split_once('-') {
        let first_byte_pos = if start_str.is_empty() {
            None
        } else {
            start_str.parse().ok()
        };

        let last_byte_pos = if end_str.is_empty() {
            None
        } else {
            end_str.parse().ok()
        };

        return (first_byte_pos, last_byte_pos);
    }

    (None, None)
}

// Helper function to get request range - mimics httpbin's get_request_range
fn get_request_range(req: &HttpRequest, upper_bound: usize) -> (usize, usize) {
    let (first_byte_pos, last_byte_pos) = if let Some(range_header) = req.headers().get("Range") {
        if let Ok(range_str) = range_header.to_str() {
            parse_request_range(range_str)
        } else {
            (None, None)
        }
    } else {
        (None, None)
    };

    let (first_byte_pos, last_byte_pos) = match (first_byte_pos, last_byte_pos) {
        (None, None) => {
            // Request full range
            (0, upper_bound - 1)
        }
        (None, Some(suffix_length)) => {
            // Request the last X bytes (suffix-byte-range-spec: "-500")
            let first_pos = upper_bound.saturating_sub(suffix_length);
            (first_pos, upper_bound - 1)
        }
        (Some(start), None) => {
            // Request from X to end
            (start, upper_bound - 1)
        }
        (Some(start), Some(end)) => {
            // Request specific range
            (start, end)
        }
    };

    (first_byte_pos, last_byte_pos)
}

pub async fn uuid_handler(_req: HttpRequest) -> Result<HttpResponse> {
    let uuid = Uuid::new_v4();
    Ok(HttpResponse::Ok().json(json!({
        "uuid": uuid.to_string()
    })))
}

pub async fn base64_handler(_req: HttpRequest, path: web::Path<String>) -> Result<HttpResponse> {
    let encoded_value = path.into_inner();

    match general_purpose::STANDARD.decode(&encoded_value) {
        Ok(decoded_bytes) => match String::from_utf8(decoded_bytes) {
            Ok(decoded_string) => Ok(HttpResponse::Ok()
                .content_type("text/plain; charset=utf-8")
                .body(decoded_string)),
            Err(e) => Ok(HttpResponse::Ok()
                .content_type("application/octet-stream")
                .body(e.into_bytes())),
        },
        Err(_) => Ok(HttpResponse::BadRequest().json(json!({
            "error": "Invalid base64 data"
        }))),
    }
}

/// POST /base64 - decode the base64 request body and return it as text/plain (httpbin #616).
pub async fn base64_post_handler(body: web::Bytes) -> Result<HttpResponse> {
    match general_purpose::STANDARD.decode(&body) {
        Ok(decoded_bytes) => match String::from_utf8(decoded_bytes) {
            Ok(decoded_string) => Ok(HttpResponse::Ok()
                .content_type("text/plain; charset=utf-8")
                .body(decoded_string)),
            Err(e) => Ok(HttpResponse::Ok()
                .content_type("application/octet-stream")
                .body(e.into_bytes())),
        },
        Err(_) => Ok(HttpResponse::BadRequest().json(json!({
            "error": "Invalid base64 data"
        }))),
    }
}

pub async fn bytes_handler(
    _req: HttpRequest,
    path: web::Path<usize>,
    query: web::Query<BytesQuery>,
    config: web::Data<AppConfig>,
) -> Result<HttpResponse> {
    let n = path.into_inner();
    // httpbin #594: reject over-limit requests with a clear error instead of
    // silently truncating, consistent with /range/{numbytes}.
    if n > config.max_bytes {
        return Ok(HttpResponse::NotFound().body(format!(
            "number of bytes must be in the range (0, {}]",
            config.max_bytes
        )));
    }

    // Generate random bytes using the same method as httpbin
    let random_bytes: Vec<u8> = if let Some(seed) = query.seed {
        let mut rng = StdRng::seed_from_u64(seed);
        (0..n).map(|_| rng.random_range(0..=255)).collect()
    } else {
        let mut rng = rand::rng();
        (0..n).map(|_| rng.random_range(0..=255)).collect()
    };

    Ok(HttpResponse::Ok()
        .content_type("application/octet-stream")
        .body(random_bytes))
}

pub async fn stream_bytes_handler(
    _req: HttpRequest,
    path: web::Path<usize>,
    query: web::Query<StreamBytesQuery>,
    config: web::Data<AppConfig>,
) -> Result<HttpResponse> {
    let n = path.into_inner();
    // httpbin #594: reject over-limit requests with a clear error instead of
    // silently truncating, consistent with /range/{numbytes}.
    if n > config.max_bytes {
        return Ok(HttpResponse::NotFound().body(format!(
            "number of bytes must be in the range (0, {}]",
            config.max_bytes
        )));
    }

    // Parse chunk_size parameter
    let chunk_size = query.chunk_size.unwrap_or(10 * 1024).max(1);

    // Initialize RNG with seed if provided
    let seed = query.seed;

    let stream = async_stream::stream! {
        let mut chunks = Vec::new();

        if let Some(seed) = seed {
            let mut rng = StdRng::seed_from_u64(seed);
            for _ in 0..n {
                chunks.push(rng.random_range(0..=255));

                if chunks.len() == chunk_size {
                    yield Ok::<_, actix_web::Error>(Bytes::from(chunks.clone()));
                    chunks.clear();
                }
            }
        } else {
            let mut rng = rand::rng();
            for _ in 0..n {
                chunks.push(rng.random_range(0..=255));

                if chunks.len() == chunk_size {
                    yield Ok::<_, actix_web::Error>(Bytes::from(chunks.clone()));
                    chunks.clear();
                }
            }
        }

        // Yield remaining bytes if any
        if !chunks.is_empty() {
            yield Ok::<_, actix_web::Error>(Bytes::from(chunks));
        }
    };

    Ok(HttpResponse::Ok()
        .content_type("application/octet-stream")
        .streaming(stream))
}

pub async fn stream_handler(
    req: HttpRequest,
    path: web::Path<usize>,
    config: web::Data<AppConfig>,
) -> Result<HttpResponse> {
    let n = path.into_inner();
    let n = n.min(100); // Limit to 100 lines

    // Extract request information similar to httpbin's get_dict("url", "args", "headers", "origin")
    let base_response = extract_get_request_info(&req, &config.exclude_headers);

    let stream = futures_util::stream::iter((0..n).map(move |i| {
        let response = json!({
            "url": base_response.url,
            "args": base_response.args,
            "headers": base_response.headers,
            "origin": base_response.origin,
            "id": i
        });

        // Format as JSON string with newline, matching httpbin's json.dumps(response) + "\n"
        Ok::<_, actix_web::Error>(Bytes::from(format!("{}\n", response)))
    }));

    Ok(HttpResponse::Ok()
        .content_type("application/json")
        .streaming(stream))
}

pub async fn range_handler(
    req: HttpRequest,
    path: web::Path<usize>,
    query: web::Query<RangeQuery>,
    config: web::Data<AppConfig>,
) -> Result<HttpResponse> {
    let numbytes = path.into_inner();

    // Check bounds first like httpbin; the cap is the configured --max-bytes
    // (httpbin #594), consistent with /bytes and /stream-bytes.
    if numbytes == 0 || numbytes > config.max_bytes {
        return Ok(HttpResponse::NotFound()
            .append_header(("ETag", format!("range{}", numbytes)))
            .append_header(("Accept-Ranges", "bytes"))
            .body(format!(
                "number of bytes must be in the range (0, {}]",
                config.max_bytes
            )));
    }

    let chunk_size = query.chunk_size.unwrap_or(10 * 1024).max(1);
    let duration = query.duration.unwrap_or(0.0);

    // Extract range information from headers using httpbin-compatible logic
    let (first_byte_pos, last_byte_pos) = get_request_range(&req, numbytes);

    // Validate range like httpbin
    if first_byte_pos > last_byte_pos || first_byte_pos >= numbytes || last_byte_pos >= numbytes {
        return Ok(HttpResponse::RangeNotSatisfiable()
            .append_header(("ETag", format!("range{}", numbytes)))
            .append_header(("Accept-Ranges", "bytes"))
            .append_header(("Content-Range", format!("bytes */{}", numbytes)))
            .append_header(("Content-Length", "0"))
            .finish());
    }

    let range_length = (last_byte_pos + 1) - first_byte_pos;
    let pause_per_byte = if range_length > 0 {
        Duration::from_secs_f64(duration / range_length as f64)
    } else {
        Duration::ZERO
    };

    // Create streaming response
    let stream = async_stream::stream! {
        let mut chunks = Vec::new();

        for i in first_byte_pos..=last_byte_pos {
            // Use deterministic data generation like httpbin: ord("a") + (i % 26)
            // This ensures consistent data for the same byte position across requests
            chunks.push(b'a' + (i % 26) as u8);

            if chunks.len() == chunk_size || i == last_byte_pos {
                yield Ok::<_, actix_web::Error>(Bytes::from(chunks.clone()));

                // Apply timing delay if specified
                if pause_per_byte.as_nanos() > 0 && !chunks.is_empty() {
                    tokio::time::sleep(pause_per_byte * chunks.len() as u32).await;
                }

                chunks.clear();
            }
        }
    };

    let content_range = format!("bytes {}-{}/{}", first_byte_pos, last_byte_pos, numbytes);

    // Determine status code: 200 for full content, 206 for partial content
    let is_full_content = first_byte_pos == 0 && last_byte_pos == (numbytes - 1);
    let status = if is_full_content {
        StatusCode::OK
    } else {
        StatusCode::PARTIAL_CONTENT
    };

    Ok(HttpResponseBuilder::new(status)
        .content_type("application/octet-stream")
        .append_header(("ETag", format!("range{}", numbytes)))
        .append_header(("Accept-Ranges", "bytes"))
        .append_header(("Content-Length", range_length.to_string()))
        .append_header(("Content-Range", content_range))
        .body(SizedStream::new(range_length as u64, Box::pin(stream))))
}

pub async fn links_handler(
    _req: HttpRequest,
    path: web::Path<(usize, usize)>,
) -> Result<HttpResponse> {
    let (n, offset) = path.into_inner();
    let n = n.clamp(1, 200); // Limit to between 1 and 200 links

    let mut html = String::from("<!DOCTYPE html><html><head><title>Links</title></head><body>");

    for i in 0..n {
        if i == offset {
            html.push_str(&format!("{}<br>", i));
        } else {
            html.push_str(&format!("<a href='/links/{}/{}'>{}</a><br>", n, i, i));
        }
    }

    html.push_str("</body></html>");

    Ok(HttpResponse::Ok().content_type("text/html").body(html))
}

pub async fn links_redirect_handler(
    _req: HttpRequest,
    path: web::Path<usize>,
) -> Result<HttpResponse> {
    let n = path.into_inner();
    Ok(HttpResponse::Found()
        .append_header(("Location", format!("/links/{}/0", n)))
        .body(""))
}

pub async fn drip_handler(
    _req: HttpRequest,
    query: web::Query<DripQuery>,
    config: web::Data<AppConfig>,
) -> Result<HttpResponse> {
    let duration = query.duration.unwrap_or(2.0);
    let numbytes = query.numbytes.unwrap_or(10);
    let code = query.code.unwrap_or(200);
    let delay = query.delay.unwrap_or(0.0);

    // Validate parameters
    if numbytes == 0 {
        return Ok(HttpResponse::BadRequest().json(json!({
            "error": "number of bytes must be positive"
        })));
    }

    // Reject over-limit requests with a clear error instead of silently
    // clamping, consistent with /bytes, /stream-bytes, and /range (httpbin #594).
    if numbytes > config.max_bytes {
        return Ok(HttpResponse::NotFound().json(json!({
            "error": format!("number of bytes must be in the range (0, {}]", config.max_bytes)
        })));
    }

    // Validate status code
    let status = StatusCode::from_u16(code).unwrap_or(StatusCode::OK);

    // Initial delay
    if delay > 0.0 {
        sleep(Duration::from_secs_f64(delay)).await;
    }

    // Calculate pause between bytes
    let pause = if numbytes == 1 {
        Duration::from_secs_f64(duration)
    } else {
        Duration::from_secs_f64(duration / (numbytes as f64 - 1.0))
    };

    // Create streaming response
    let stream = async_stream::stream! {
        for i in 0..numbytes {
            // Yield a single '*' byte
            yield Ok::<_, actix_web::Error>(Bytes::from("*"));

            // Don't pause after the last byte
            if i < numbytes - 1 && pause.as_nanos() > 0 {
                sleep(pause).await;
            }
        }
    };

    let mut builder = HttpResponseBuilder::new(status);
    builder.content_type("application/octet-stream");
    // Chunked transfer-encoding (no Content-Length) when requested (httpbin #479);
    // otherwise SizedStream sets Content-Length.
    let response = if query.chunked.unwrap_or(false) {
        builder.streaming(stream)
    } else {
        builder.body(SizedStream::new(numbytes as u64, Box::pin(stream)))
    };
    Ok(response)
}

pub async fn delay_handler_get(
    req: HttpRequest,
    path: web::Path<f64>,
    config: web::Data<AppConfig>,
) -> Result<HttpResponse> {
    let delay_seconds = path.into_inner().min(10.0); // Max 10 seconds

    sleep(Duration::from_secs_f64(delay_seconds)).await;

    let mut request_info = extract_request_info(&req, None, &config.exclude_headers);
    fix_request_info_url(&req, &mut request_info);
    Ok(HttpResponse::Ok().json(request_info))
}

pub async fn delay_handler(
    req: HttpRequest,
    path: web::Path<f64>,
    body: String,
    config: web::Data<AppConfig>,
) -> Result<HttpResponse> {
    let delay_seconds = path.into_inner().min(10.0); // Max 10 seconds

    sleep(Duration::from_secs_f64(delay_seconds)).await;

    let mut request_info = extract_request_info(&req, Some(&body), &config.exclude_headers);
    fix_request_info_url(&req, &mut request_info);
    Ok(HttpResponse::Ok().json(request_info))
}