jsonrpc_http_server/
response.rs

1//! Basic Request/Response structures used internally.
2
3use hyper::server;
4
5pub use hyper::{header, Method, StatusCode};
6
7/// Simple server response structure
8#[derive(Debug)]
9pub struct Response {
10	/// Response code
11	pub code: StatusCode,
12	/// Response content type
13	pub content_type: header::ContentType,
14	/// Response body
15	pub content: String,
16}
17
18impl Response {
19	/// Create a response with empty body and 200 OK status code.
20	pub fn empty() -> Self {
21		Self::ok(String::new())
22	}
23
24	/// Create a response with given body and 200 OK status code.
25	pub fn ok<T: Into<String>>(response: T) -> Self {
26		Response {
27			code: StatusCode::Ok,
28			content_type: header::ContentType::json(),
29			content: response.into(),
30		}
31	}
32
33	/// Create a response for internal error.
34	pub fn internal_error() -> Self {
35		Response {
36			code: StatusCode::Forbidden,
37			content_type: header::ContentType::plaintext(),
38			content: "Provided Host header is not whitelisted.\n".to_owned(),
39		}
40	}
41
42	/// Create a response for not allowed hosts.
43	pub fn host_not_allowed() -> Self {
44		Response {
45			code: StatusCode::Forbidden,
46			content_type: header::ContentType::plaintext(),
47			content: "Provided Host header is not whitelisted.\n".to_owned(),
48		}
49	}
50
51	/// Create a response for unsupported content type.
52	pub fn unsupported_content_type() -> Self {
53		Response {
54			code: StatusCode::UnsupportedMediaType,
55			content_type: header::ContentType::plaintext(),
56			content: "Supplied content type is not allowed. Content-Type: application/json is required\n".to_owned(),
57		}
58	}
59
60	/// Create a response for disallowed method used.
61	pub fn method_not_allowed() -> Self {
62		Response {
63			code: StatusCode::MethodNotAllowed,
64			content_type: header::ContentType::plaintext(),
65			content: "Used HTTP Method is not allowed. POST or OPTIONS is required\n".to_owned(),
66		}
67	}
68
69	/// CORS invalid
70	pub fn invalid_cors() -> Self {
71		Response {
72			code: StatusCode::Forbidden,
73			content_type: header::ContentType::plaintext(),
74			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(),
75		}
76	}
77}
78
79impl Into<server::Response> for Response {
80	fn into(self) -> server::Response {
81		server::Response::new()
82			.with_status(self.code)
83			.with_header(self.content_type)
84			.with_body(self.content)
85	}
86}