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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
use self::errors::*;
use crate::Result;
use serde_derive::Deserialize;
#[derive(Debug, Default, Deserialize)]
pub struct Configuration {
pub server: ServerConfiguration,
}
#[derive(Debug, Deserialize)]
pub struct ServerConfiguration {
pub host: String,
pub port: u16,
}
impl Default for ServerConfiguration {
fn default() -> Self {
Self {
host: "0.0.0.0".to_string(),
port: 17000,
}
}
}
const CONFIGURATION_FILE: &str = include_str!("config.yml");
pub fn get_configuration() -> Result<Configuration> {
serde_yaml::from_str(CONFIGURATION_FILE).map_err(|e| parse_error(e.to_string()))
}
mod errors {
use crate::DmntkError;
#[derive(Debug, PartialEq)]
enum ConfigurationError {
ParseError(String),
}
impl From<ConfigurationError> for DmntkError {
fn from(e: ConfigurationError) -> Self {
DmntkError::new("ConfigurationError", &format!("{}", e))
}
}
impl std::fmt::Display for ConfigurationError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConfigurationError::ParseError(reason) => {
write!(f, "parsing configuration file failed with reason: {}", reason)
}
}
}
}
pub fn parse_error(reason: String) -> DmntkError {
ConfigurationError::ParseError(reason).into()
}
}
#[cfg(test)]
mod tests {
use crate::config::{get_configuration, ServerConfiguration};
#[test]
fn test_default_server_configuration() {
let server_configuration = ServerConfiguration::default();
assert_eq!("0.0.0.0", server_configuration.host);
assert_eq!(17000, server_configuration.port);
}
#[test]
fn test_configuration_file() {
let configuration = get_configuration().unwrap();
assert_eq!("127.0.0.1", configuration.server.host);
assert_eq!(12000, configuration.server.port);
}
}