How do I set content-type to "text/html" using warp crate?

I have written some code (see below) using the warp crate to return an HTTP response. However, it does not automatically set the content-type to "text/html".

I did some research and found out I need to use the warp::reply::html function.

How do I convert my existing code to use the warp::reply::html?

pub async fn start_warp_server() {
    let get_html_page = warp::path!(i64)
        .map(|site_id| generate_html_body(site_id));

    let get_article_page = warp::path!(i64 / u8)
        .map(|site_id, article_index| generate_article_body(site_id, article_index));

    let routes = warp::get()
        .and(get_html_page)
        .or(get_article_page);

    let server: SocketAddr = conf_settings::LISTENING_SERVER_PORT
        .parse()
        .expect("Unable to parse LISTENING_SERVER_PORT");

    warp::serve(routes).run(server).await;
}

fn generate_html_body(x: i64) -> String {
    // generate HTML body here
}

fn generate_article_body(x: i64, y: u8) -> String {
    // generate HTML body here
}

Note: the code the generate the HTML is executed dynamically (ie. it is not static HTML text).

You can wrap your response with this function.

Couldn't figure out how to make it work... that's why I wrote my question here.

Like this:

let get_html_page = warp::path!(i64)
        .map(|site_id| warp::reply::html(generate_html_body(site_id)));
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.