jsonrpc_http_server/
response.rspub use hyper::{self, header::HeaderValue, Body, Method, StatusCode};
#[derive(Debug)]
pub struct Response {
pub code: StatusCode,
pub content_type: HeaderValue,
pub content: String,
}
impl Response {
pub fn empty() -> Self {
Self::ok(String::new())
}
pub fn ok<T: Into<String>>(response: T) -> Self {
Response {
code: StatusCode::OK,
content_type: HeaderValue::from_static("application/json; charset=utf-8"),
content: response.into(),
}
}
pub fn internal_error<T: Into<String>>(msg: T) -> Self {
Response {
code: StatusCode::INTERNAL_SERVER_ERROR,
content_type: plain_text(),
content: format!("Internal Server Error: {}", msg.into()),
}
}
pub fn service_unavailable<T: Into<String>>(msg: T) -> Self {
Response {
code: StatusCode::SERVICE_UNAVAILABLE,
content_type: HeaderValue::from_static("application/json; charset=utf-8"),
content: msg.into(),
}
}
pub fn host_not_allowed() -> Self {
Response {
code: StatusCode::FORBIDDEN,
content_type: plain_text(),
content: "Provided Host header is not whitelisted.\n".to_owned(),
}
}
pub fn unsupported_content_type() -> Self {
Response {
code: StatusCode::UNSUPPORTED_MEDIA_TYPE,
content_type: plain_text(),
content: "Supplied content type is not allowed. Content-Type: application/json is required\n".to_owned(),
}
}
pub fn method_not_allowed() -> Self {
Response {
code: StatusCode::METHOD_NOT_ALLOWED,
content_type: plain_text(),
content: "Used HTTP Method is not allowed. POST or OPTIONS is required\n".to_owned(),
}
}
pub fn invalid_allow_origin() -> Self {
Response {
code: StatusCode::FORBIDDEN,
content_type: plain_text(),
content: "Origin of the request is not whitelisted. CORS headers would not be sent and any side-effects were cancelled as well.\n".to_owned(),
}
}
pub fn invalid_allow_headers() -> Self {
Response {
code: StatusCode::FORBIDDEN,
content_type: plain_text(),
content: "Requested headers are not allowed for CORS. CORS headers would not be sent and any side-effects were cancelled as well.\n".to_owned(),
}
}
pub fn bad_request<S: Into<String>>(msg: S) -> Self {
Response {
code: StatusCode::BAD_REQUEST,
content_type: plain_text(),
content: msg.into(),
}
}
pub fn too_large<S: Into<String>>(msg: S) -> Self {
Response {
code: StatusCode::PAYLOAD_TOO_LARGE,
content_type: plain_text(),
content: msg.into(),
}
}
pub(crate) fn closing() -> Self {
Response {
code: StatusCode::SERVICE_UNAVAILABLE,
content_type: plain_text(),
content: "Server is closing.".into(),
}
}
}
fn plain_text() -> HeaderValue {
HeaderValue::from_static("text/plain; charset=utf-8")
}
impl From<Response> for hyper::Response<Body> {
fn from(res: Response) -> hyper::Response<Body> {
hyper::Response::builder()
.status(res.code)
.header("content-type", res.content_type)
.body(res.content.into())
.expect("Unable to parse response body for type conversion")
}
}