Skip to main content

http_meta/
http_meta.rs

1use susydev_jsonrpc_http_server::susydev_jsonrpc_core::*;
2use susydev_jsonrpc_http_server::{cors::AccessControlAllowHeaders, hyper, RestApi, ServerBuilder};
3
4#[derive(Default, Clone)]
5struct Meta {
6	auth: Option<String>,
7}
8
9impl Metadata for Meta {}
10
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}