Search code examples
rustactix-web

How to set the status code of a response?


I'm using actix for a web application I'm working on, and I'm trying to set the status code 409 to a response, but I don't know how to do that. Something a bit like this:

HttpResponse::StatusCode(409).json(Status{
            value: val,
            isOn: true
})

Solution

  • There are several ways to explicitly set the status code. The easiest way is to make use of actix-web's implementation of Responder for (T, StatusCode) whenever T: Responder. Assuming Status is some custom struct implementing Serialize, you should be able to write something like

    use actix_web::{HttpRequest, Responder, http, web};
    
    fn foo(req: HttpRequest) -> impl Responder {
        (
            web::Json(Status {
                value: val,
                isOn: true,
            }),
            http::StatusCode::CONFLICT,
        )
    }