openlegends_client/
connection.rs

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
pub mod error;
pub use error::Error;

use native_tls::{TlsConnector, TlsStream};
use std::{
    io::{Read, Write},
    net::TcpStream,
    str,
};

pub struct Connection {
    stream: TlsStream<TcpStream>,
}

impl Connection {
    pub fn new(host: &str, port: u16) -> Result<Self, Error> {
        match TcpStream::connect(format!("{}:{}", host, port)) {
            Ok(connection) => match TlsConnector::builder()
                .danger_accept_invalid_certs(true)
                .build()
            {
                Ok(connector) => match connector.connect(host, connection) {
                    Ok(stream) => Ok(Self { stream }),
                    Err(e) => Err(Error::TlsConnection(e)),
                },
                Err(e) => Err(Error::TlsConnector(e)),
            },
            Err(e) => Err(Error::TcpStream(e)),
        }
    }

    pub fn request(&mut self, query: &str) -> Result<String, Error> {
        match self.stream.write_all(query.as_bytes()) {
            Ok(()) => {
                let mut buffer = [0; 1024];
                match self.stream.read(&mut buffer) {
                    Ok(read) => match str::from_utf8(&buffer[..read]) {
                        Ok(response) => Ok(response.to_string()),
                        Err(e) => Err(Error::Utf8(e)),
                    },
                    Err(e) => Err(Error::TcpStream(e)),
                }
            }
            Err(e) => Err(Error::TcpStream(e)),
        }
    }
}