~int80h/gemserv

ref: e5c44c2c536bfd08d885907c6f23a33f44383862 gemserv/src/conn.rs -rw-r--r-- 1.5 KiB
e5c44c2cint 80h Fixed redirect and scgi path when its the root url 6 months ago
                                                                                
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
51
52
53
54
55
use std::io;
use std::marker::Unpin;
use std::net::SocketAddr;

use tokio::net::TcpStream;
use tokio::io::AsyncRead;
use tokio::io::{AsyncWrite, AsyncWriteExt};
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?;
        }

        futures_util::future::poll_fn(|ctx| std::pin::Pin::new(&mut self.stream).poll_shutdown(ctx)).await.unwrap();

        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?;
        futures_util::future::poll_fn(|ctx| std::pin::Pin::new(&mut self.stream).poll_shutdown(ctx)).await.unwrap();
        Ok(())
    }
}