openlegends_client/
connection.rspub 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)),
}
}
}