-
Notifications
You must be signed in to change notification settings - Fork 0
/
conn.rs
50 lines (43 loc) · 1.26 KB
/
conn.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
48
49
50
use std::io;
use std::marker::Unpin;
use std::net::SocketAddr;
use tokio::net::TcpStream;
use tokio::prelude::*;
use tokio_openssl::SslStream;
use crate::status::Status;
pub struct Connection {
pub stream: SslStream<TcpStream>,
pub peer_addr: SocketAddr,
}
impl Connection {
pub async fn send_status(&mut self, stat: Status, meta: Option<&str>) -> Result<(), io::Error> {
self.send_body(stat, meta, None).await?;
Ok(())
}
pub async fn send_body(
&mut self,
stat: Status,
meta: Option<&str>,
body: Option<String>,
) -> Result<(), io::Error> {
let meta = match meta {
Some(m) => m,
None => &stat.to_str(),
};
self.send_raw(format!("{} {}\r\n", stat as u8, meta).as_bytes())
.await?;
if let Some(b) = body {
self.send_raw(b.as_bytes()).await?;
}
Ok(())
}
pub async fn send_raw(&mut self, body: &[u8]) -> Result<(), io::Error> {
self.stream.write_all(body).await?;
self.stream.flush().await?;
Ok(())
}
pub async fn send_stream<S: AsyncRead + Unpin>(&mut self, reader: &mut S) -> Result<(), io::Error> {
tokio::io::copy(reader, &mut self.stream).await?;
Ok(())
}
}