From 327b4fffa3381345ee4620df7e9998efe2aa9454 Mon Sep 17 00:00:00 2001 From: Kaleb Elwert Date: Thu, 25 Jun 2020 10:08:10 -0700 Subject: [PATCH] feat: Add `Status::to_http` (#376) --- tonic/src/server/grpc.rs | 22 +++------------------- tonic/src/status.rs | 15 +++++++++++++++ 2 files changed, 18 insertions(+), 19 deletions(-) diff --git a/tonic/src/server/grpc.rs b/tonic/src/server/grpc.rs index 3ef566476..7852d7fe7 100644 --- a/tonic/src/server/grpc.rs +++ b/tonic/src/server/grpc.rs @@ -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}; @@ -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 { - 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(&self, req: Request) -> Result, http::Response> { 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) diff --git a/tonic/src/status.rs b/tonic/src/status.rs index 2cc4515bc..53c7f8550 100644 --- a/tonic/src/status.rs +++ b/tonic/src/status.rs @@ -1,3 +1,4 @@ +use crate::body::BoxBody; use crate::metadata::MetadataMap; use bytes::Bytes; use http::header::{HeaderMap, HeaderValue}; @@ -464,6 +465,20 @@ impl Status { metadata: metadata, } } + + /// Build an `http::Response` from the given `Status`. + pub fn to_http(self) -> http::Response { + 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 {