use fastly::http::body::PrefixString;
use fastly::http::HeaderValue;
use fastly::{Error, Request, Response};

fn header_val(header: Option<&HeaderValue>) -> String {
    header
        .and_then(|h| h.to_str().ok())
        .map(|h| h.to_string())
        .unwrap_or_else(String::new)
}

fn body_prefix_val(prefix: Result<PrefixString, std::str::Utf8Error>) -> String {
    prefix
        .map(|body_prefix| body_prefix.to_string())
        .unwrap_or_else(|_| String::new())
}

#[fastly::main]
fn main(mut req: Request) -> Result<Response, Error> {
    println!("Request:");
    println!("User-Agent: {}", header_val(req.get_header("User-Agent")));
    println!(
        "POST body: {}",
        body_prefix_val(req.try_get_body_prefix_str_mut(1024))
    );

    let mut beresp = req.send("origin_0")?;

    println!("Response:");
    println!(
        "Content-Type: {}",
        header_val(beresp.get_header("content-type"))
    );
    println!(
        "First 20 bytes of response: {}",
        body_prefix_val(beresp.try_get_body_prefix_str_mut(20))
    );

    Ok(beresp)
}