openlegends_client/
connection.rs

1pub mod error;
2pub use error::Error;
3
4use native_tls::{TlsConnector, TlsStream};
5use std::{
6    io::{Read, Write},
7    net::TcpStream,
8    str,
9};
10
11pub struct Connection {
12    stream: TlsStream<TcpStream>,
13}
14
15impl Connection {
16    pub fn new(host: &str, port: u16) -> Result<Self, Error> {
17        match TcpStream::connect(format!("{}:{}", host, port)) {
18            Ok(connection) => match TlsConnector::builder()
19                .danger_accept_invalid_certs(true)
20                .build()
21            {
22                Ok(connector) => match connector.connect(host, connection) {
23                    Ok(stream) => Ok(Self { stream }),
24                    Err(e) => Err(Error::TlsConnection(e)),
25                },
26                Err(e) => Err(Error::TlsConnector(e)),
27            },
28            Err(e) => Err(Error::TcpStream(e)),
29        }
30    }
31
32    pub fn request(&mut self, query: &str) -> Result<String, Error> {
33        match self.stream.write_all(query.as_bytes()) {
34            Ok(()) => {
35                let mut buffer = [0; 1024];
36                match self.stream.read(&mut buffer) {
37                    Ok(read) => match str::from_utf8(&buffer[..read]) {
38                        Ok(response) => Ok(response.to_string()),
39                        Err(e) => Err(Error::Utf8(e)),
40                    },
41                    Err(e) => Err(Error::TcpStream(e)),
42                }
43            }
44            Err(e) => Err(Error::TcpStream(e)),
45        }
46    }
47}