💾 Archived View for 80h.dev › projects › gemserv › files › src › conn.rs.gemini captured on 2022-06-12 at 00:48:42. Gemini links have been rewritten to link to archived content
⬅️ Previous capture (2022-03-01)
-=-=-=-=-=-=-
01 use std::io;
02 use std::marker::Unpin;
03 use std::net::SocketAddr;
04
05 use tokio::net::TcpStream;
06 use tokio::prelude::*;
07 use tokio_openssl::SslStream;
08
09 use crate::status::Status;
10
11 pub struct Connection {
12 pub stream: SslStream<TcpStream>,
13 pub peer_addr: SocketAddr,
14 }
15
16 impl Connection {
17 pub async fn send_status(&mut self, stat: Status, meta: Option<&str>) -> Result<(), io::Error> {
18 self.send_body(stat, meta, None).await?;
19 Ok(())
20 }
21
22 pub async fn send_body(
23 &mut self,
24 stat: Status,
25 meta: Option<&str>,
26 body: Option<String>,
27 ) -> Result<(), io::Error> {
28 let meta = match meta {
29 Some(m) => m,
30 None => &stat.to_str(),
31 };
32 self.send_raw(format!("{} {}\r\n", stat as u8, meta).as_bytes())
33 .await?;
34 if let Some(b) = body {
35 self.send_raw(b.as_bytes()).await?;
36 }
37 Ok(())
38 }
39
40 pub async fn send_raw(&mut self, body: &[u8]) -> Result<(), io::Error> {
41 self.stream.write_all(body).await?;
42 self.stream.flush().await?;
43 Ok(())
44 }
45
46 pub async fn send_stream<S: AsyncRead + Unpin>(&mut self, reader: &mut S) -> Result<(), io::Error> {
47 tokio::io::copy(reader, &mut self.stream).await?;
48 Ok(())
49 }
50 }