pub trait Responder {
type Body: MessageBody + 'static;
// Required method
fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body>;
// Provided method
fn customize(self) -> CustomizeResponder<Self>
where Self: Sized { ... }
}
Expand description
Trait implemented by types that can be converted to an HTTP response.
Any types that implement this trait can be used in the return type of a handler. Since handlers
will only have one return type, it is idiomatic to use opaque return types -> impl Responder
.
§Implementations
It is often not required to implement Responder
for your own types due to a broad base of
built-in implementations:
HttpResponse
andHttpResponseBuilder
Option<R>
whereR: Responder
Result<R, E>
whereR: Responder
andE: ResponseError
(R, StatusCode)
whereR: Responder
&'static str
,String
,&'_ String
,Cow<'_, str>
,ByteString
&'static [u8]
,Vec<u8>
,Bytes
,BytesMut
Json<T>
andForm<T>
whereT: Serialize
Either<L, R>
whereL: Serialize
andR: Serialize
CustomizeResponder<R>
actix_files::NamedFile
- Experimental responders from
actix-web-lab
- Third party integrations may also have implemented
Responder
where appropriate. For example, HTML templating engines.
§Customizing Responder Output
Calling .customize()
on any responder type will wrap it in a
CustomizeResponder
capable of overriding various parts of the response such as the status
code and header map.
Required Associated Types§
type Body: MessageBody + 'static
Required Methods§
sourcefn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body>
fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body>
Convert self to HttpResponse
.
Provided Methods§
sourcefn customize(self) -> CustomizeResponder<Self>where
Self: Sized,
fn customize(self) -> CustomizeResponder<Self>where
Self: Sized,
Wraps responder to allow alteration of its response.
See CustomizeResponder
docs for more details on its capabilities.
§Examples
use actix_web::{Responder, http::StatusCode, test::TestRequest};
let responder = "Hello world!"
.customize()
.with_status(StatusCode::BAD_REQUEST)
.insert_header(("x-hello", "world"));
let request = TestRequest::default().to_http_request();
let response = responder.respond_to(&request);
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
assert_eq!(response.headers().get("x-hello").unwrap(), "world");