1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-12-01 22:11:20 +00:00

add helper converters into response

This commit is contained in:
Nikolay Kim 2017-11-28 13:52:53 -08:00
parent a3022e6d88
commit 706e2a07de
3 changed files with 127 additions and 16 deletions

View file

@ -64,8 +64,8 @@ extern crate actix;
extern crate actix_web; extern crate actix_web;
use actix_web::prelude::*; use actix_web::prelude::*;
fn index(req: HttpRequest) -> Result<HttpResponse> { fn index(req: HttpRequest) -> &'static str {
Ok(httpcodes::HTTPOk.with_body("Hello world!")) "Hello world!"
} }
fn main() { fn main() {

View file

@ -47,11 +47,11 @@ struct AppState {
counter: Cell<usize>, counter: Cell<usize>,
} }
fn index(req: HttpRequest<AppState>) -> HttpResponse { fn index(req: HttpRequest<AppState>) -> String {
let count = req.state().counter.get() + 1; // <- get count let count = req.state().counter.get() + 1; // <- get count
req.state().counter.set(count); // <- store new count in state req.state().counter.set(count); // <- store new count in state
httpcodes::HTTPOk.with_body( // <- response with count
format!("Num of requests: {}", count)) format!("Request number: {}", count) // <- response with count
} }
fn main() { fn main() {

View file

@ -3,6 +3,7 @@ use std::{io, mem, str, fmt};
use std::convert::Into; use std::convert::Into;
use cookie::CookieJar; use cookie::CookieJar;
use bytes::{Bytes, BytesMut};
use http::{StatusCode, Version, HeaderMap, HttpTryFrom, Error as HttpError}; use http::{StatusCode, Version, HeaderMap, HttpTryFrom, Error as HttpError};
use http::header::{self, HeaderName, HeaderValue}; use http::header::{self, HeaderName, HeaderValue};
use serde_json; use serde_json;
@ -204,16 +205,6 @@ impl HttpResponse {
} }
} }
/// Helper conversion implementation
impl<I: Into<HttpResponse>, E: Into<Error>> From<Result<I, E>> for HttpResponse {
fn from(res: Result<I, E>) -> Self {
match res {
Ok(val) => val.into(),
Err(err) => err.into().into(),
}
}
}
impl From<HttpResponse> for Frame { impl From<HttpResponse> for Frame {
fn from(resp: HttpResponse) -> Frame { fn from(resp: HttpResponse) -> Frame {
Frame::Message(resp) Frame::Message(resp)
@ -458,10 +449,74 @@ fn parts<'a>(parts: &'a mut Option<Parts>, err: &Option<HttpError>) -> Option<&'
parts.as_mut() parts.as_mut()
} }
/// Helper converters
impl<I: Into<HttpResponse>, E: Into<Error>> From<Result<I, E>> for HttpResponse {
fn from(res: Result<I, E>) -> Self {
match res {
Ok(val) => val.into(),
Err(err) => err.into().into(),
}
}
}
impl From<&'static str> for HttpResponse {
fn from(val: &'static str) -> HttpResponse {
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(val)
.into()
}
}
impl From<&'static [u8]> for HttpResponse {
fn from(val: &'static [u8]) -> HttpResponse {
HttpResponse::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(val)
.into()
}
}
impl From<String> for HttpResponse {
fn from(val: String) -> HttpResponse {
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(val)
.into()
}
}
impl<'a> From<&'a String> for HttpResponse {
fn from(val: &'a String) -> HttpResponse {
HttpResponse::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(val)
.into()
}
}
impl From<Bytes> for HttpResponse {
fn from(val: Bytes) -> HttpResponse {
HttpResponse::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(val)
.into()
}
}
impl From<BytesMut> for HttpResponse {
fn from(val: BytesMut) -> HttpResponse {
HttpResponse::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(val)
.into()
}
}
#[cfg(test)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
use bytes::Bytes; use body::Binary;
#[test] #[test]
fn test_body() { fn test_body() {
@ -518,4 +573,60 @@ mod tests {
assert_eq!(ct, header::HeaderValue::from_static("text/json")); assert_eq!(ct, header::HeaderValue::from_static("text/json"));
assert_eq!(*resp.body(), Body::from(Bytes::from_static(b"[\"v1\",\"v2\",\"v3\"]"))); assert_eq!(*resp.body(), Body::from(Bytes::from_static(b"[\"v1\",\"v2\",\"v3\"]")));
} }
impl Body {
pub(crate) fn binary(&self) -> Option<&Binary> {
match *self {
Body::Binary(ref bin) => Some(bin),
_ => None,
}
}
}
#[test]
fn test_into_response() {
let resp: HttpResponse = "test".into();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("text/plain; charset=utf-8"));
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from("test"));
let resp: HttpResponse = b"test".as_ref().into();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("application/octet-stream"));
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from(b"test".as_ref()));
let resp: HttpResponse = "test".to_owned().into();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("text/plain; charset=utf-8"));
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from("test".to_owned()));
let resp: HttpResponse = (&"test".to_owned()).into();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("text/plain; charset=utf-8"));
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from((&"test".to_owned())));
let b = Bytes::from_static(b"test");
let resp: HttpResponse = b.into();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("application/octet-stream"));
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from(Bytes::from_static(b"test")));
let b = BytesMut::from("test");
let resp: HttpResponse = b.into();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::CONTENT_TYPE).unwrap(),
header::HeaderValue::from_static("application/octet-stream"));
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().binary().unwrap(), &Binary::from(BytesMut::from("test")));
}
} }