Struct ServerBuilder

Source
pub struct ServerBuilder<M: Metadata = (), S: Middleware<M> = Noop> { /* private fields */ }
Expand description

Convenient JSON-RPC HTTP Server builder.

Implementations§

Source§

impl<M: Metadata + Default, S: Middleware<M>> ServerBuilder<M, S>

Source

pub fn new<T>(handler: T) -> Self
where T: Into<MetaIoHandler<M, S>>,

Creates new ServerBuilder for given IoHandler.

By default:

  1. Server is not sending any CORS headers.
  2. Server is validating Host header.
Examples found in repository?
examples/http_async.rs (line 10)
4fn main() {
5	let mut io = IoHandler::default();
6	io.add_method("say_hello", |_params| {
7		futures::finished(Value::String("hello".to_owned()))
8	});
9
10	let server = ServerBuilder::new(io)
11		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null]))
12		.start_http(&"127.0.0.1:3030".parse().unwrap())
13		.expect("Unable to start RPC server");
14
15	server.wait();
16}
More examples
Hide additional examples
examples/server.rs (line 8)
4fn main() {
5	let mut io = IoHandler::default();
6	io.add_method("say_hello", |_params: Params| Ok(Value::String("hello".to_string())));
7
8	let server = ServerBuilder::new(io)
9		.threads(3)
10		.rest_api(RestApi::Unsecure)
11		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Any]))
12		.start_http(&"127.0.0.1:3030".parse().unwrap())
13		.expect("Unable to start RPC server");
14
15	server.wait();
16}
examples/http_middleware.rs (line 11)
5fn main() {
6	let mut io = IoHandler::default();
7	io.add_method("say_hello", |_params| {
8		futures::finished(Value::String("hello".to_owned()))
9	});
10
11	let server = ServerBuilder::new(io)
12		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null]))
13		.request_middleware(|request: hyper::Request<hyper::Body>| {
14			if request.uri() == "/status" {
15				Response::ok("Server running OK.").into()
16			} else {
17				request.into()
18			}
19		})
20		.rest_api(RestApi::Unsecure)
21		.start_http(&"127.0.0.1:3030".parse().unwrap())
22		.expect("Unable to start RPC server");
23
24	server.wait();
25}
examples/http_meta.rs (line 25)
11fn main() {
12	let mut io = MetaIoHandler::default();
13
14	io.add_method_with_meta("say_hello", |_params: Params, meta: Meta| {
15		let auth = meta.auth.unwrap_or_else(String::new);
16		if auth.as_str() == "let-me-in" {
17			Ok(Value::String("Hello World!".to_owned()))
18		} else {
19			Ok(Value::String(
20				"Please send a valid Bearer token in Authorization header.".to_owned(),
21			))
22		}
23	});
24
25	let server = ServerBuilder::new(io)
26		.cors_allow_headers(AccessControlAllowHeaders::Only(vec!["Authorization".to_owned()]))
27		.rest_api(RestApi::Unsecure)
28		// You can also implement `MetaExtractor` trait and pass a struct here.
29		.meta_extractor(|req: &hyper::Request<hyper::Body>| {
30			let auth = req
31				.headers()
32				.get(hyper::header::AUTHORIZATION)
33				.map(|h| h.to_str().unwrap_or("").to_owned());
34
35			Meta { auth }
36		})
37		.start_http(&"127.0.0.1:3030".parse().unwrap())
38		.expect("Unable to start RPC server");
39
40	server.wait();
41}
Source§

impl<M: Metadata, S: Middleware<M>> ServerBuilder<M, S>

Source

pub fn with_meta_extractor<T, E>(handler: T, extractor: E) -> Self
where T: Into<MetaIoHandler<M, S>>, E: MetaExtractor<M>,

Creates new ServerBuilder for given IoHandler.

By default:

  1. Server is not sending any CORS headers.
  2. Server is validating Host header.
Source

pub fn event_loop_executor(self, executor: TaskExecutor) -> Self

Utilize existing event loop executor to poll RPC results.

Applies only to 1 of the threads. Other threads will spawn their own Event Loops.

Source

pub fn rest_api(self, rest_api: RestApi) -> Self

Enable the REST -> RPC converter.

Allows you to invoke RPCs by sending POST /<method>/<param1>/<param2> requests (with no body). Disabled by default.

Examples found in repository?
examples/server.rs (line 10)
4fn main() {
5	let mut io = IoHandler::default();
6	io.add_method("say_hello", |_params: Params| Ok(Value::String("hello".to_string())));
7
8	let server = ServerBuilder::new(io)
9		.threads(3)
10		.rest_api(RestApi::Unsecure)
11		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Any]))
12		.start_http(&"127.0.0.1:3030".parse().unwrap())
13		.expect("Unable to start RPC server");
14
15	server.wait();
16}
More examples
Hide additional examples
examples/http_middleware.rs (line 20)
5fn main() {
6	let mut io = IoHandler::default();
7	io.add_method("say_hello", |_params| {
8		futures::finished(Value::String("hello".to_owned()))
9	});
10
11	let server = ServerBuilder::new(io)
12		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null]))
13		.request_middleware(|request: hyper::Request<hyper::Body>| {
14			if request.uri() == "/status" {
15				Response::ok("Server running OK.").into()
16			} else {
17				request.into()
18			}
19		})
20		.rest_api(RestApi::Unsecure)
21		.start_http(&"127.0.0.1:3030".parse().unwrap())
22		.expect("Unable to start RPC server");
23
24	server.wait();
25}
examples/http_meta.rs (line 27)
11fn main() {
12	let mut io = MetaIoHandler::default();
13
14	io.add_method_with_meta("say_hello", |_params: Params, meta: Meta| {
15		let auth = meta.auth.unwrap_or_else(String::new);
16		if auth.as_str() == "let-me-in" {
17			Ok(Value::String("Hello World!".to_owned()))
18		} else {
19			Ok(Value::String(
20				"Please send a valid Bearer token in Authorization header.".to_owned(),
21			))
22		}
23	});
24
25	let server = ServerBuilder::new(io)
26		.cors_allow_headers(AccessControlAllowHeaders::Only(vec!["Authorization".to_owned()]))
27		.rest_api(RestApi::Unsecure)
28		// You can also implement `MetaExtractor` trait and pass a struct here.
29		.meta_extractor(|req: &hyper::Request<hyper::Body>| {
30			let auth = req
31				.headers()
32				.get(hyper::header::AUTHORIZATION)
33				.map(|h| h.to_str().unwrap_or("").to_owned());
34
35			Meta { auth }
36		})
37		.start_http(&"127.0.0.1:3030".parse().unwrap())
38		.expect("Unable to start RPC server");
39
40	server.wait();
41}
Source

pub fn health_api<A, B, T>(self, health_api: T) -> Self
where T: Into<Option<(A, B)>>, A: Into<String>, B: Into<String>,

Enable health endpoint.

Allows you to expose one of the methods under GET /<path> The method will be invoked with no parameters. Error returned from the method will be converted to status 500 response.

Expects a tuple with (<path>, <rpc-method-name>).

Source

pub fn keep_alive(self, val: bool) -> Self

Enables or disables HTTP keep-alive.

Default is true.

Source

pub fn threads(self, threads: usize) -> Self

Sets number of threads of the server to run.

Panics when set to 0.

Examples found in repository?
examples/server.rs (line 9)
4fn main() {
5	let mut io = IoHandler::default();
6	io.add_method("say_hello", |_params: Params| Ok(Value::String("hello".to_string())));
7
8	let server = ServerBuilder::new(io)
9		.threads(3)
10		.rest_api(RestApi::Unsecure)
11		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Any]))
12		.start_http(&"127.0.0.1:3030".parse().unwrap())
13		.expect("Unable to start RPC server");
14
15	server.wait();
16}
Source

pub fn cors( self, cors_domains: DomainsValidation<AccessControlAllowOrigin>, ) -> Self

Configures a list of allowed CORS origins.

Examples found in repository?
examples/http_async.rs (line 11)
4fn main() {
5	let mut io = IoHandler::default();
6	io.add_method("say_hello", |_params| {
7		futures::finished(Value::String("hello".to_owned()))
8	});
9
10	let server = ServerBuilder::new(io)
11		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null]))
12		.start_http(&"127.0.0.1:3030".parse().unwrap())
13		.expect("Unable to start RPC server");
14
15	server.wait();
16}
More examples
Hide additional examples
examples/server.rs (line 11)
4fn main() {
5	let mut io = IoHandler::default();
6	io.add_method("say_hello", |_params: Params| Ok(Value::String("hello".to_string())));
7
8	let server = ServerBuilder::new(io)
9		.threads(3)
10		.rest_api(RestApi::Unsecure)
11		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Any]))
12		.start_http(&"127.0.0.1:3030".parse().unwrap())
13		.expect("Unable to start RPC server");
14
15	server.wait();
16}
examples/http_middleware.rs (line 12)
5fn main() {
6	let mut io = IoHandler::default();
7	io.add_method("say_hello", |_params| {
8		futures::finished(Value::String("hello".to_owned()))
9	});
10
11	let server = ServerBuilder::new(io)
12		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null]))
13		.request_middleware(|request: hyper::Request<hyper::Body>| {
14			if request.uri() == "/status" {
15				Response::ok("Server running OK.").into()
16			} else {
17				request.into()
18			}
19		})
20		.rest_api(RestApi::Unsecure)
21		.start_http(&"127.0.0.1:3030".parse().unwrap())
22		.expect("Unable to start RPC server");
23
24	server.wait();
25}
Source

pub fn cors_max_age<T: Into<Option<u32>>>(self, cors_max_age: T) -> Self

Configure CORS AccessControlMaxAge header returned.

Passing Some(millis) informs the client that the CORS preflight request is not necessary for at least millis ms. Disabled by default.

Source

pub fn cors_allow_headers( self, allowed_headers: AccessControlAllowHeaders, ) -> Self

Configure the CORS AccessControlAllowHeaders header which are allowed.

Examples found in repository?
examples/http_meta.rs (line 26)
11fn main() {
12	let mut io = MetaIoHandler::default();
13
14	io.add_method_with_meta("say_hello", |_params: Params, meta: Meta| {
15		let auth = meta.auth.unwrap_or_else(String::new);
16		if auth.as_str() == "let-me-in" {
17			Ok(Value::String("Hello World!".to_owned()))
18		} else {
19			Ok(Value::String(
20				"Please send a valid Bearer token in Authorization header.".to_owned(),
21			))
22		}
23	});
24
25	let server = ServerBuilder::new(io)
26		.cors_allow_headers(AccessControlAllowHeaders::Only(vec!["Authorization".to_owned()]))
27		.rest_api(RestApi::Unsecure)
28		// You can also implement `MetaExtractor` trait and pass a struct here.
29		.meta_extractor(|req: &hyper::Request<hyper::Body>| {
30			let auth = req
31				.headers()
32				.get(hyper::header::AUTHORIZATION)
33				.map(|h| h.to_str().unwrap_or("").to_owned());
34
35			Meta { auth }
36		})
37		.start_http(&"127.0.0.1:3030".parse().unwrap())
38		.expect("Unable to start RPC server");
39
40	server.wait();
41}
Source

pub fn request_middleware<T: RequestMiddleware>(self, middleware: T) -> Self

Configures request middleware

Examples found in repository?
examples/http_middleware.rs (lines 13-19)
5fn main() {
6	let mut io = IoHandler::default();
7	io.add_method("say_hello", |_params| {
8		futures::finished(Value::String("hello".to_owned()))
9	});
10
11	let server = ServerBuilder::new(io)
12		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null]))
13		.request_middleware(|request: hyper::Request<hyper::Body>| {
14			if request.uri() == "/status" {
15				Response::ok("Server running OK.").into()
16			} else {
17				request.into()
18			}
19		})
20		.rest_api(RestApi::Unsecure)
21		.start_http(&"127.0.0.1:3030".parse().unwrap())
22		.expect("Unable to start RPC server");
23
24	server.wait();
25}
Source

pub fn meta_extractor<T: MetaExtractor<M>>(self, extractor: T) -> Self

Configures metadata extractor

Examples found in repository?
examples/http_meta.rs (lines 29-36)
11fn main() {
12	let mut io = MetaIoHandler::default();
13
14	io.add_method_with_meta("say_hello", |_params: Params, meta: Meta| {
15		let auth = meta.auth.unwrap_or_else(String::new);
16		if auth.as_str() == "let-me-in" {
17			Ok(Value::String("Hello World!".to_owned()))
18		} else {
19			Ok(Value::String(
20				"Please send a valid Bearer token in Authorization header.".to_owned(),
21			))
22		}
23	});
24
25	let server = ServerBuilder::new(io)
26		.cors_allow_headers(AccessControlAllowHeaders::Only(vec!["Authorization".to_owned()]))
27		.rest_api(RestApi::Unsecure)
28		// You can also implement `MetaExtractor` trait and pass a struct here.
29		.meta_extractor(|req: &hyper::Request<hyper::Body>| {
30			let auth = req
31				.headers()
32				.get(hyper::header::AUTHORIZATION)
33				.map(|h| h.to_str().unwrap_or("").to_owned());
34
35			Meta { auth }
36		})
37		.start_http(&"127.0.0.1:3030".parse().unwrap())
38		.expect("Unable to start RPC server");
39
40	server.wait();
41}
Source

pub fn allow_only_bind_host(self) -> Self

Allow connections only with Host header set to binding address.

Source

pub fn allowed_hosts(self, allowed_hosts: DomainsValidation<Host>) -> Self

Specify a list of valid Host headers. Binding address is allowed automatically.

Source

pub fn max_request_body_size(self, val: usize) -> Self

Sets the maximum size of a request body in bytes (default is 5 MiB).

Source

pub fn start_http(self, addr: &SocketAddr) -> Result<Server>

Start this JSON-RPC HTTP server trying to bind to specified SocketAddr.

Examples found in repository?
examples/http_async.rs (line 12)
4fn main() {
5	let mut io = IoHandler::default();
6	io.add_method("say_hello", |_params| {
7		futures::finished(Value::String("hello".to_owned()))
8	});
9
10	let server = ServerBuilder::new(io)
11		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null]))
12		.start_http(&"127.0.0.1:3030".parse().unwrap())
13		.expect("Unable to start RPC server");
14
15	server.wait();
16}
More examples
Hide additional examples
examples/server.rs (line 12)
4fn main() {
5	let mut io = IoHandler::default();
6	io.add_method("say_hello", |_params: Params| Ok(Value::String("hello".to_string())));
7
8	let server = ServerBuilder::new(io)
9		.threads(3)
10		.rest_api(RestApi::Unsecure)
11		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Any]))
12		.start_http(&"127.0.0.1:3030".parse().unwrap())
13		.expect("Unable to start RPC server");
14
15	server.wait();
16}
examples/http_middleware.rs (line 21)
5fn main() {
6	let mut io = IoHandler::default();
7	io.add_method("say_hello", |_params| {
8		futures::finished(Value::String("hello".to_owned()))
9	});
10
11	let server = ServerBuilder::new(io)
12		.cors(DomainsValidation::AllowOnly(vec![AccessControlAllowOrigin::Null]))
13		.request_middleware(|request: hyper::Request<hyper::Body>| {
14			if request.uri() == "/status" {
15				Response::ok("Server running OK.").into()
16			} else {
17				request.into()
18			}
19		})
20		.rest_api(RestApi::Unsecure)
21		.start_http(&"127.0.0.1:3030".parse().unwrap())
22		.expect("Unable to start RPC server");
23
24	server.wait();
25}
examples/http_meta.rs (line 37)
11fn main() {
12	let mut io = MetaIoHandler::default();
13
14	io.add_method_with_meta("say_hello", |_params: Params, meta: Meta| {
15		let auth = meta.auth.unwrap_or_else(String::new);
16		if auth.as_str() == "let-me-in" {
17			Ok(Value::String("Hello World!".to_owned()))
18		} else {
19			Ok(Value::String(
20				"Please send a valid Bearer token in Authorization header.".to_owned(),
21			))
22		}
23	});
24
25	let server = ServerBuilder::new(io)
26		.cors_allow_headers(AccessControlAllowHeaders::Only(vec!["Authorization".to_owned()]))
27		.rest_api(RestApi::Unsecure)
28		// You can also implement `MetaExtractor` trait and pass a struct here.
29		.meta_extractor(|req: &hyper::Request<hyper::Body>| {
30			let auth = req
31				.headers()
32				.get(hyper::header::AUTHORIZATION)
33				.map(|h| h.to_str().unwrap_or("").to_owned());
34
35			Meta { auth }
36		})
37		.start_http(&"127.0.0.1:3030".parse().unwrap())
38		.expect("Unable to start RPC server");
39
40	server.wait();
41}

Auto Trait Implementations§

§

impl<M, S> Freeze for ServerBuilder<M, S>

§

impl<M = (), S = Noop> !RefUnwindSafe for ServerBuilder<M, S>

§

impl<M, S> Send for ServerBuilder<M, S>

§

impl<M, S> Sync for ServerBuilder<M, S>

§

impl<M, S> Unpin for ServerBuilder<M, S>

§

impl<M = (), S = Noop> !UnwindSafe for ServerBuilder<M, S>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.