rudis_http/
connection.rs

1use tokio::io::{AsyncReadExt, AsyncWriteExt, Result};
2use tokio::net::TcpStream;
3
4pub struct Connection {
5    stream: TcpStream,
6}
7
8impl Connection {
9    pub async fn new(stream: TcpStream) -> Result<Connection> {
10        Ok(Connection { stream })
11    }
12
13    pub async fn read_stream(&mut self) -> Result<Vec<u8>> {
14        let mut buf = [0u8; 1024];
15        let n = self.stream.read(&mut buf).await?;
16        Ok(buf[..n].to_vec())
17    }
18
19    pub async fn write_stream(&mut self, data: &[u8]) -> Result<()> {
20        self.stream
21            .write_all(&Connection::make_response(data))
22            .await?;
23        Ok(())
24    }
25
26    fn make_response(data: &[u8]) -> Vec<u8> {
27        let mut response = Vec::new();
28        response.extend_from_slice(b"HTTP/1.1 200 OK\r\n");
29        response.extend_from_slice(b"Content-Type: application/json\r\n");
30        response.extend_from_slice(b"Content-Length: ");
31        response.extend_from_slice(data.len().to_string().as_bytes());
32        response.extend_from_slice(b"\r\n\r\n");
33        response.extend_from_slice(data);
34        response
35    }
36}