~garritfra/taurus

taurus: Add utils module, move write_file to GeminiResponse v1 NEEDS REVISION

Alexey Yerin: 1
 Add utils module, move write_file to GeminiResponse

 3 files changed, 43 insertions(+), 38 deletions(-)
#348164 ci.yml success
> What do you think of renaming this to "io"?
This name doesn't really fit because this should be a generic file for
helper functions, not only I/O.
Export patchset (mbox)
How do I use this?

Copy & paste the following snippet into your terminal to import this patchset into git:

curl -s https://lists.sr.ht/~garritfra/taurus/patches/15207/mbox | git am -3
Learn more about email & git
View this thread in the archives

[PATCH taurus] Add utils module, move write_file to GeminiResponse Export this patch

Signed-off-by: Alexey Yerin <yerinalexey98fd@gmail.com>
---
 src/gemini.rs | 26 ++++++++++++++++++++++++++
 src/main.rs   | 43 +++++--------------------------------------
 src/utils.rs  | 12 ++++++++++++
 3 files changed, 43 insertions(+), 38 deletions(-)
 create mode 100644 src/utils.rs

diff --git a/src/gemini.rs b/src/gemini.rs
index 8e4e8ec..bd8afa5 100644
--- a/src/gemini.rs
+++ b/src/gemini.rs
@@ -1,5 +1,8 @@
use crate::error::{TaurusError, TaurusResult};
use crate::logger;
use crate::utils;
use native_tls::TlsStream;
use std::path;
use std::{io::Write, net::TcpStream, str::FromStr};
use url::Url;

@@ -83,6 +86,29 @@ impl GeminiResponse {
        }
    }

    pub fn from_file(path: &str) -> TaurusResult<GeminiResponse> {
        let extension = path::Path::new(path)
            .extension()
            .unwrap_or_else(|| std::ffi::OsStr::new(""));

        let mime_type = match &*extension.to_string_lossy() {
            "gmi" => "text/gemini; charset=utf-8",
            ext => mime_guess::from_ext(ext)
                .first_raw()
                .unwrap_or("text/plain"),
        };

        match utils::read_file(path) {
            Ok(buf) => Ok(GeminiResponse::success(buf, mime_type)),
            Err(err) => {
                // Cannot read file or it doesn't exist
                logger::error(format!("{}: {}", path, err));

                Ok(GeminiResponse::not_found())
            }
        }
    }

    pub fn send(&self, mut stream: TlsStream<TcpStream>) -> TaurusResult<usize> {
        let mut buf: Vec<u8> = Vec::new();

diff --git a/src/main.rs b/src/main.rs
index 90de12e..c829da2 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -5,13 +5,13 @@ mod config;
mod error;
mod gemini;
mod logger;
mod utils;

use error::{TaurusError, TaurusResult};
use gemini::{GeminiRequest, GeminiResponse};
use native_tls::{Identity, TlsAcceptor, TlsStream};
use std::{
    fs::File,
    io::{self, Read},
    io::Read,
    net::{TcpListener, TcpStream},
    path,
    sync::Arc,
@@ -58,7 +58,7 @@ fn run() -> TaurusResult<()> {
        .unwrap_or_else(|| "/var/www/gemini".to_owned());

    // Read certificate
    let identity = read_file(&cert_file).map_err(TaurusError::NoIdentity)?;
    let identity = utils::read_file(&cert_file).map_err(TaurusError::NoIdentity)?;

    let identity = Identity::from_pkcs12(&identity, &config.certificate_password)?;

@@ -93,40 +93,7 @@ fn run() -> TaurusResult<()> {
    Ok(())
}

/// Helper function to read a file into Vec
fn read_file(file_path: &str) -> Result<Vec<u8>, io::Error> {
    let mut file = File::open(file_path)?;
    let mut buf = Vec::new();

    file.read_to_end(&mut buf)?;

    Ok(buf)
}

/// Send file as a response
fn write_file(path: &str) -> TaurusResult<GeminiResponse> {
    let extension = path::Path::new(path)
        .extension()
        .unwrap_or_else(|| std::ffi::OsStr::new(""));

    let mime_type = match &*extension.to_string_lossy() {
        "gmi" => "text/gemini; charset=utf-8",
        ext => mime_guess::from_ext(ext)
            .first_raw()
            .unwrap_or("text/plain"),
    };

    match read_file(path) {
        Ok(buf) => Ok(GeminiResponse::success(buf, mime_type)),
        Err(err) => {
            // Cannot read file or it doesn't exist
            logger::error(format!("{}: {}", path, err));

            Ok(GeminiResponse::not_found())
        }
    }
}

fn handle_client(mut stream: TlsStream<TcpStream>, static_root: &str) -> TaurusResult<usize> {
    let mut buffer = [0; 1024];

@@ -153,9 +120,9 @@ fn handle_client(mut stream: TlsStream<TcpStream>, static_root: &str) -> TaurusR
        if path.exists() {
            // If it's a directory, try to find index.gmi
            if path.is_dir() {
                write_file(&path.join("index.gmi").to_string_lossy())?.send(stream)
                GeminiResponse::from_file(&path.join("index.gmi").to_string_lossy())?.send(stream)
            } else {
                write_file(&path.to_string_lossy())?.send(stream)
                GeminiResponse::from_file(&path.to_string_lossy())?.send(stream)
            }
        } else {
            GeminiResponse::not_found().send(stream)
diff --git a/src/utils.rs b/src/utils.rs
new file mode 100644
index 0000000..1eb7ddc
--- /dev/null
+++ b/src/utils.rs
@@ -0,0 +1,12 @@
use std::fs::File;
use std::io::{self, Read};

/// Read a file into Vec
pub fn read_file(file_path: &str) -> Result<Vec<u8>, io::Error> {
    let mut file = File::open(file_path)?;
    let mut buf = Vec::new();

    file.read_to_end(&mut buf)?;

    Ok(buf)
}
-- 
2.29.2
builds.sr.ht
taurus/patches/ci.yml: SUCCESS in 1m25s

[Add utils module, move write_file to GeminiResponse][0] from [Alexey Yerin][1]

[0]: https://lists.sr.ht/~garritfra/taurus/patches/15207
[1]: mailto:yerinalexey98fd@gmail.com

✓ #348164 SUCCESS taurus/patches/ci.yml https://builds.sr.ht/~garritfra/job/348164