Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the easiest way to get the HTML output of an actix-web endpoint handler to be rendered properly?

I've defined an endpoint with actix-web like so:

#[derive(Deserialize)]
struct RenderInfo {
    filename: String,
}

fn render(info: actix_web::Path<RenderInfo>) -> Result<String> {
    // ...
}
App::new()
    .middleware(middleware::Logger::Default())
    .resource("/{filename}", |r| r.get().with(render))

The problem I've run into is that the raw HTML gets displayed in the browser rather than being rendered. I assume the content-type is not being set properly.

Most of the actix-web examples I saw used impl Responder for the return type, but I wasn't able to figure out how to fix the type inference issues that created. The reason seems to have something to do with file operations returning a standard failure::Error-based type. It looks like actix_web requires implementation of a special WebError to block unintended propagation of errors. For this particular instance, I don't really care, because it's more of an internal tool.

like image 605
spease Avatar asked Nov 07 '18 00:11

spease


1 Answers

From the actix-web examples, use HttpResponse:

fn welcome(req: &HttpRequest) -> Result<HttpResponse> {
    println!("{:?}", req);

    // session
    let mut counter = 1;
    if let Some(count) = req.session().get::<i32>("counter")? {
        println!("SESSION value: {}", count);
        counter = count + 1;
    }

    // set counter to session
    req.session().set("counter", counter)?;

    // response
    Ok(HttpResponse::build(StatusCode::OK)
        .content_type("text/html; charset=utf-8")
        .body(include_str!("../static/welcome.html")))
}
like image 162
Shepmaster Avatar answered Nov 18 '22 18:11

Shepmaster