Response

We can get response reference as function handler paramer:

#[fn_handler]
async fn hello_world(res: &mut Response) {
    res.render_plain_text("hello world!");
}

When server get a client request and in it’s whole process cycle, any handler or middlewares can write to response object. In middleware, you may want to skip all reset middlewares and handler, you can use FlowCtrl:

#[fn_handler]
async fn hello_world(res: &mut Response, ctrl: &mut FlowCtrl) {
    ctrl.skip_reset();
    res.render_plain_text("hello world!");
}

Write content

Write content is straightforward:

  • Write plain text

    res.render_plain_text("hello world!");
    
  • Write serializable type as json format

    #[derive(Serialize, Debug)]
    struct User {
        name: String,
    }
    let user = User{name: "jobs"};
    res.render_json(&user);
    
  • Write html text

    res.render_html("<html><body>hello</body></html>");
    

Write http error

  • Use set_http_error can write a http error to response.

    use salvo::http::errors::*;
    res.set_http_error(InternalServerError().with_summary("error when serialize object to json"))
    
  • If we don’t want to customize error message, just use set_http_code.

    use salvo::http::StatusCode;
    res.set_status_code(StatusCode::BAD_REQUEST);