Consolidate results to one struct
[hlquery.git] / src / main.rs
1 use std::fmt;
2 use std::fmt::Display;
3 use std::error::Error;
4 use std::env::args;
5 use std::net::{SocketAddr, SocketAddrV4, ToSocketAddrs};
6 use serde::{Serialize, Serializer};
7 use a2s::A2SClient;
8 use crate::HLQueryError::A2SError;
9
10 #[derive(Debug, Serialize)]
11 struct HLQueryResult {
12 info: Result<a2s::info::Info, HLQueryError>,
13 rules: Result<Vec<a2s::rules::Rule>, HLQueryError>,
14 players: Result<Vec<a2s::players::Player>, HLQueryError>
15 }
16
17 impl HLQueryResult {
18 fn new(a2s_client: &A2SClient, server: SocketAddrV4) -> Self {
19 Self {
20 info: a2s_client.info(server).map_err(From::from),
21 rules: a2s_client.rules(server).map_err(From::from),
22 players: a2s_client.players(server).map_err(From::from)
23 }
24 }
25 }
26
27 #[derive(Debug)]
28 enum HLQueryError {
29 A2SError(a2s::errors::Error)
30 }
31
32 impl Display for HLQueryError {
33 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
34 match self {
35 A2SError(e) => write!(f, "{}", e)
36 }
37 }
38 }
39
40 impl Error for HLQueryError {}
41
42 impl Serialize for HLQueryError {
43 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
44 where
45 S: Serializer,
46 {
47 serializer.serialize_str(&format!("{self}"))
48 }
49 }
50
51 impl From<a2s::errors::Error> for HLQueryError {
52 fn from(e: a2s::errors::Error) -> Self {
53 Self::A2SError(e)
54 }
55 }
56
57
58 fn main() {
59 let client = A2SClient::new().unwrap();
60 let addresses = args().skip(1)
61 .flat_map(|arg| arg.to_socket_addrs())
62 .flat_map(|iter_addr| iter_addr.flat_map(|sa| match sa {
63 SocketAddr::V4(sa4) => Some(sa4),
64 _ => None
65 })
66 );
67
68 for address in addresses {
69
70 println!("Querying address: {}", address);
71
72 let result = HLQueryResult::new(&client, address);
73 println!("{}\n", serde_json::to_string_pretty(&result).unwrap());
74
75 }
76 }