use crate::Response;
pub trait IntoResponse {
fn into_response(self) -> Response;
}
impl<T: Into<Response>> IntoResponse for T {
fn into_response(self) -> Response {
self.into()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::StatusCode;
#[test]
fn test_string_into_response() {
let res = "hello".to_string().into_response();
assert_eq!(res.status(), StatusCode::OK);
}
#[test]
fn test_str_into_response() {
let res = "hello".into_response();
assert_eq!(res.status(), StatusCode::OK);
}
#[test]
fn test_response_into_response() {
let res = Response::empty().into_response();
assert_eq!(res.status(), StatusCode::OK);
}
#[test]
fn test_silent_error_into_response() {
let err = crate::SilentError::business_error(StatusCode::NOT_FOUND, "not found");
let res = err.into_response();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
enum AppError {
NotFound,
BadRequest(String),
}
impl From<AppError> for Response {
fn from(e: AppError) -> Self {
match e {
AppError::NotFound => Response::empty().with_status(StatusCode::NOT_FOUND),
AppError::BadRequest(msg) => {
Response::text(&msg).with_status(StatusCode::BAD_REQUEST)
}
}
}
}
#[test]
fn test_custom_error_into_response() {
let res = AppError::NotFound.into_response();
assert_eq!(res.status(), StatusCode::NOT_FOUND);
let res = AppError::BadRequest("invalid".to_string()).into_response();
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
}