繁体   English   中英

使actix-web终结点处理程序的HTML输出正确呈现的最简单方法是什么?

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

我已经使用actix-web定义了一个端点,如下所示:

#[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))

我遇到的问题是原始HTML会在浏览器中显示而不是呈现。 我认为内容类型设置不正确。

我看到的大多数actix-web示例都将impl Responder用于返回类型,但是我无法弄清楚如何解决所创建的类型推断问题。 原因似乎与文件操作返回标准的基于failure::Error的类型有关。 看来actix_web需要实现特殊的WebError来阻止意外的错误传播。 对于这个特定实例,我并不在乎,因为它更多是一种内部工具。

actix-web示例中 ,使用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")))
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM