Use configuration file (config.json)
This commit is contained in:
36
src/config.rs
Normal file
36
src/config.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use serde::Deserialize;
|
||||
|
||||
//// Config Example
|
||||
// {
|
||||
// "nick": "RustBot",
|
||||
// "ident": "icedragon",
|
||||
// "gecos": "IceDragon's Rust client thingy",
|
||||
// "server": "irc.quickfox.net:6667"
|
||||
// }
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct IrcConfig {
|
||||
pub nick: String, // "RustBot"
|
||||
pub ident: String, // "icedragon"
|
||||
pub gecos: String, // "IceDragon's Rust Bot Thing"
|
||||
pub server: String, // "irc.quickfox.net:6667"
|
||||
}
|
||||
|
||||
/// Load IRC configuration from a given file:
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```rust,nodoc
|
||||
/// let conf = config::load_config("config.json").expect("failed to load config");
|
||||
///
|
||||
/// ```
|
||||
pub fn load_config(path: &str) -> io::Result<IrcConfig> {
|
||||
let json_string = fs::read_to_string(path)?;
|
||||
match serde_json::from_str(&json_string) {
|
||||
Ok(conf) => Ok(conf),
|
||||
Err(e) => Err(io::Error::new(io::ErrorKind::InvalidInput, e.to_string())),
|
||||
}
|
||||
}
|
||||
14
src/main.rs
14
src/main.rs
@@ -2,6 +2,8 @@ use std::net::TcpStream;
|
||||
use std::io::{self, Read, Write};
|
||||
use std::ops::ControlFlow;
|
||||
|
||||
mod config;
|
||||
|
||||
#[derive(Debug)]
|
||||
#[allow(dead_code)]
|
||||
enum IrcClientMessage<'msg> {
|
||||
@@ -280,7 +282,15 @@ impl Client {
|
||||
}
|
||||
|
||||
fn main() -> io::Result<()> {
|
||||
let mut client = Client::new("RustBot", "icedragon", "IceDragon's Rust client thingy");
|
||||
client.connect("irc.quickfox.net:6667")?;
|
||||
const CONFIG_FILE: &str = "config.json";
|
||||
|
||||
// load configuration
|
||||
println!("[++] Loading configuration from {CONFIG_FILE}...");
|
||||
let config = config::load_config(CONFIG_FILE)?;
|
||||
|
||||
// create & connect client
|
||||
println!("[++] Creating & connecting bot client (nick: {})", config.nick);
|
||||
let mut client = Client::new(&config.nick, &config.ident, &config.gecos);
|
||||
client.connect(&config.server)?;
|
||||
client.serve()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user