1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use hyper::{self, Server};
use hyper::rt::Future;
use hyper::service::service_fn;
use response::response;
use sled;
use std::net::SocketAddr;
use std::sync::Arc;
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct Config {
pub addr: SocketAddr,
}
#[derive(Clone, Default, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct ConfigBuilder {
pub addr: Option<SocketAddr>,
}
pub fn config() -> ConfigBuilder {
Default::default()
}
impl Config {
pub const DEFAULT_IP: [u8; 4] = [127, 0, 0, 1];
pub const DEFAULT_PORT: u16 = 3000;
pub const DEFAULT_ADDR: ([u8; 4], u16) = (Self::DEFAULT_IP, Self::DEFAULT_PORT);
}
impl ConfigBuilder {
pub fn addr<T>(&mut self, addr: T) -> &mut Self
where
T: Into<SocketAddr>,
{
self.addr = Some(addr.into());
self
}
pub fn build(&mut self) -> Config {
let addr = self.addr.take().unwrap_or_else(|| Config::DEFAULT_ADDR.into());
Config { addr }
}
}
pub fn new(config: Config, tree: Arc<sled::Tree>) -> impl Future<Item = (), Error = hyper::Error> {
Server::bind(&config.addr)
.serve(move || {
let tree = tree.clone();
service_fn(move |req| {
response(req, tree.clone())
})
})
}
pub fn run(config: Config, tree: Arc<sled::Tree>) {
let server = new(config, tree)
.map_err(|e| eprintln!("error occurred: {}", e));
hyper::rt::run(server);
}