Skip to content

Commit

Permalink
feat: Add Status::to_http (#376)
Browse files Browse the repository at this point in the history
  • Loading branch information
belak authored Jun 25, 2020
1 parent 80e90e3 commit 327b4ff
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 19 deletions.
22 changes: 3 additions & 19 deletions tonic/src/server/grpc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use crate::{
codec::{encode_server, Codec, Streaming},
interceptor::Interceptor,
server::{ClientStreamingService, ServerStreamingService, StreamingService, UnaryService},
Code, Request, Response, Status,
Code, Request, Status,
};
use futures_core::TryStream;
use futures_util::{future, stream, TryStreamExt};
Expand Down Expand Up @@ -210,31 +210,15 @@ where

http::Response::from_parts(parts, BoxBody::new(body))
}
Err(status) => Self::map_status(status),
Err(status) => status.to_http(),
}
}

fn map_status(status: Status) -> http::Response<BoxBody> {
let (mut parts, _body) = Response::new(()).into_http().into_parts();

parts.headers.insert(
http::header::CONTENT_TYPE,
http::header::HeaderValue::from_static("application/grpc"),
);

status.add_header(&mut parts.headers).unwrap();

http::Response::from_parts(parts, BoxBody::empty())
}

fn intercept_request<A>(&self, req: Request<A>) -> Result<Request<A>, http::Response<BoxBody>> {
if let Some(interceptor) = &self.interceptor {
match interceptor.call(req) {
Ok(req) => Ok(req),
Err(status) => {
let res = Self::map_status(status);
return Err(res);
}
Err(status) => Err(status.to_http()),
}
} else {
Ok(req)
Expand Down
15 changes: 15 additions & 0 deletions tonic/src/status.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use crate::body::BoxBody;
use crate::metadata::MetadataMap;
use bytes::Bytes;
use http::header::{HeaderMap, HeaderValue};
Expand Down Expand Up @@ -464,6 +465,20 @@ impl Status {
metadata: metadata,
}
}

/// Build an `http::Response` from the given `Status`.
pub fn to_http(self) -> http::Response<BoxBody> {
let (mut parts, _body) = http::Response::new(()).into_parts();

parts.headers.insert(
http::header::CONTENT_TYPE,
http::header::HeaderValue::from_static("application/grpc"),
);

self.add_header(&mut parts.headers).unwrap();

http::Response::from_parts(parts, BoxBody::empty())
}
}

impl fmt::Debug for Status {
Expand Down

0 comments on commit 327b4ff

Please sign in to comment.