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