Skip to content

Commit

Permalink
add headers to responder impls
Browse files Browse the repository at this point in the history
  • Loading branch information
petar-dambovaliev committed Dec 5, 2021
1 parent c00f884 commit 5c27ff2
Show file tree
Hide file tree
Showing 6 changed files with 158 additions and 43 deletions.
6 changes: 5 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -27,4 +27,8 @@ pprof:

.PHONY: cloc
cloc:
cloc --exclude-dir=target .
cloc --exclude-dir=target .

.PHONY: test
test:
cargo test --all
47 changes: 32 additions & 15 deletions darpi-web/src/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,30 @@ use crate::response::{Responder, ResponderError};
use crate::Response;
use async_trait::async_trait;
use derive_more::Display;
use http::header::HeaderName;
use http::{header, HeaderMap, HeaderValue};
use hyper::Body;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize};
use serde_json::Error;
use std::{fmt, ops};

pub struct Json<T>(pub T);
pub struct Json<T> {
t: T,
hm: HeaderMap,
}

impl<T> Json<T> {
pub fn into_inner(self) -> T {
self.0
pub fn new(t: T) -> Self {
Self {
t,
hm: Default::default(),
}
}

pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
self.hm.append(key, value);
self
}

async fn deserialize_future(b: Body) -> Result<Json<T>, JsonErr>
Expand All @@ -23,7 +35,7 @@ impl<T> Json<T> {
{
let full_body = hyper::body::to_bytes(b).await?;
let ser: T = serde_json::from_slice(&full_body)?;
Ok(Json(ser))
Ok(Json::new(ser))
}
}

Expand Down Expand Up @@ -55,21 +67,21 @@ where
D: Deserializer<'de>,
{
let deser = T::deserialize(deserializer)?.into();
Ok(Json(deser))
Ok(Json::new(deser))
}
}

impl<T> ops::Deref for Json<T> {
type Target = T;

fn deref(&self) -> &T {
&self.0
&self.t
}
}

impl<T> ops::DerefMut for Json<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
&mut self.t
}
}

Expand All @@ -78,7 +90,7 @@ where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Json: {:?}", self.0)
write!(f, "Json: {:?}", self.t)
}
}

Expand All @@ -87,7 +99,7 @@ where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
fmt::Display::fmt(&self.t, f)
}
}

Expand All @@ -96,12 +108,17 @@ where
T: Serialize,
{
fn respond(self) -> Response<Body> {
match serde_json::to_string(&self.0) {
Ok(body) => Response::builder()
.header(header::CONTENT_TYPE, "application/json")
.status(self.status_code())
.body(Body::from(body))
.expect("this cannot happen"),
match serde_json::to_string(&self.t) {
Ok(body) => {
let mut rb = Response::builder()
.header(header::CONTENT_TYPE, "application/json")
.status(self.status_code());

for (hk, hv) in self.hm.iter() {
rb = rb.header(hk, hv);
}
rb.body(Body::from(body)).expect("this cannot happen")
}
Err(e) => e.respond_err(),
}
}
Expand Down
47 changes: 34 additions & 13 deletions darpi-web/src/xml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,23 +4,39 @@ use crate::Response;
use async_trait::async_trait;
use bytes::Buf;
use derive_more::Display;
use http::header::HeaderName;
use http::{header, HeaderMap, HeaderValue};
use hyper::Body;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize};
use serde_xml_rs::Error;
use std::{fmt, ops};

pub struct Xml<T>(pub T);
pub struct Xml<T> {
t: T,
hm: HeaderMap,
}

impl<T> Xml<T> {
pub fn new(t: T) -> Self {
Self {
t,
hm: Default::default(),
}
}

pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
self.hm.append(key, value);
self
}

async fn deserialize_future(b: Body) -> Result<Xml<T>, XmlErr>
where
T: DeserializeOwned,
{
let full_body = hyper::body::to_bytes(b).await?;
let ser: T = serde_xml_rs::from_reader(full_body.reader())?;
Ok(Xml(ser))
Ok(Xml::new(ser))
}
}

Expand Down Expand Up @@ -52,21 +68,21 @@ where
D: Deserializer<'de>,
{
let deser = T::deserialize(deserializer)?.into();
Ok(Xml(deser))
Ok(Xml::new(deser))
}
}

impl<T> ops::Deref for Xml<T> {
type Target = T;

fn deref(&self) -> &T {
&self.0
&self.t
}
}

impl<T> ops::DerefMut for Xml<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
&mut self.t
}
}

Expand All @@ -75,7 +91,7 @@ where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Xml: {:?}", self.0)
write!(f, "Xml: {:?}", self.t)
}
}

Expand All @@ -84,7 +100,7 @@ where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
fmt::Display::fmt(&self.t, f)
}
}

Expand All @@ -93,12 +109,17 @@ where
T: Serialize,
{
fn respond(self) -> Response<Body> {
match serde_xml_rs::to_string(&self.0) {
Ok(body) => Response::builder()
.header(header::CONTENT_TYPE, "application/xml")
.status(self.status_code())
.body(Body::from(body))
.expect("this cannot happen"),
match serde_xml_rs::to_string(&self.t) {
Ok(body) => {
let mut rb = Response::builder()
.header(header::CONTENT_TYPE, "application/xml")
.status(self.status_code());

for (hk, hv) in self.hm.iter() {
rb = rb.header(hk, hv);
}
rb.body(Body::from(body)).expect("this cannot happen")
}
Err(e) => e.respond_err(),
}
}
Expand Down
48 changes: 35 additions & 13 deletions darpi-web/src/yaml.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,23 +3,39 @@ use crate::response::{Responder, ResponderError};
use crate::Response;
use async_trait::async_trait;
use derive_more::Display;
use http::header::HeaderName;
use http::{header, HeaderMap, HeaderValue};
use hyper::Body;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize};
use serde_yaml::Error;
use std::{fmt, ops};

pub struct Yaml<T>(pub T);
pub struct Yaml<T> {
t: T,
hm: HeaderMap,
}

impl<T> Yaml<T> {
pub fn new(t: T) -> Self {
Self {
t,
hm: Default::default(),
}
}

pub fn header(mut self, key: HeaderName, value: HeaderValue) -> Self {
self.hm.append(key, value);
self
}

async fn deserialize_future(b: Body) -> Result<Yaml<T>, YamlErr>
where
T: DeserializeOwned,
{
let full_body = hyper::body::to_bytes(b).await?;
let ser: T = serde_yaml::from_slice(&full_body)?;
Ok(Yaml(ser))
Ok(Yaml::new(ser))
}
}

Expand Down Expand Up @@ -51,21 +67,21 @@ where
D: Deserializer<'de>,
{
let deser = T::deserialize(deserializer)?.into();
Ok(Yaml(deser))
Ok(Yaml::new(deser))
}
}

impl<T> ops::Deref for Yaml<T> {
type Target = T;

fn deref(&self) -> &T {
&self.0
&self.t
}
}

impl<T> ops::DerefMut for Yaml<T> {
fn deref_mut(&mut self) -> &mut T {
&mut self.0
&mut self.t
}
}

Expand All @@ -74,7 +90,7 @@ where
T: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Yaml: {:?}", self.0)
write!(f, "Yaml: {:?}", self.t)
}
}

Expand All @@ -83,7 +99,7 @@ where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
fmt::Display::fmt(&self.t, f)
}
}

Expand All @@ -92,12 +108,18 @@ where
T: Serialize,
{
fn respond(self) -> Response<Body> {
match serde_yaml::to_string(&self.0) {
Ok(body) => Response::builder()
.header(header::CONTENT_TYPE, "application/Yaml")
.status(self.status_code())
.body(Body::from(body))
.expect("this cannot happen"),
match serde_yaml::to_string(&self.t) {
Ok(body) => {
let mut rb = Response::builder()
.header(header::CONTENT_TYPE, "application/Yaml")
.status(self.status_code());

for (hk, hv) in self.hm.iter() {
rb = rb.header(hk, hv);
}

rb.body(Body::from(body)).expect("this cannot happen")
}
Err(e) => e.respond_err(),
}
}
Expand Down
9 changes: 8 additions & 1 deletion examples/responses.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
use darpi::{app, handler, App, Body, Json, Responder, Response, StatusCode};
use env_logger;
use http::header::HeaderName;
use http::HeaderValue;
use serde::Serialize;
use std::str::FromStr;

pub struct HelloWorldResp;

Expand Down Expand Up @@ -35,9 +38,13 @@ pub struct Resp {

#[handler]
async fn json() -> Json<Resp> {
Json(Resp {
Json::new(Resp {
name: "John".to_string(),
})
.header(
HeaderName::from_str("Keep-Alive").unwrap(),
HeaderValue::from_str("timeout=5").unwrap(),
)
}

#[darpi::main]
Expand Down
Loading

0 comments on commit 5c27ff2

Please sign in to comment.