From 532cc431d1c5ca1ffcf429a4ccb94edc7848fe7a Mon Sep 17 00:00:00 2001 From: metamuffin Date: Thu, 30 May 2024 00:09:11 +0200 Subject: rename filters dir --- src/modules/file.rs | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100644 src/modules/file.rs (limited to 'src/modules/file.rs') diff --git a/src/modules/file.rs b/src/modules/file.rs new file mode 100644 index 0000000..53c27f4 --- /dev/null +++ b/src/modules/file.rs @@ -0,0 +1,62 @@ +use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse}; +use crate::error::ServiceError; +use futures::Future; +use http_body_util::{combinators::BoxBody, BodyExt}; +use hyper::{ + header::{HeaderValue, CONTENT_TYPE}, + Response, +}; +use serde::Deserialize; +use serde_yaml::Value; +use std::{fs::read_to_string, path::PathBuf, pin::Pin, sync::Arc}; + +pub struct FileKind; + +#[derive(Debug, Deserialize)] +struct FileConfig { + path: Option, + content: Option, + r#type: Option, +} + +#[derive(Debug, Deserialize)] +struct File { + content: String, + r#type: String, +} + +impl NodeKind for FileKind { + fn name(&self) -> &'static str { + "file" + } + fn instanciate(&self, config: Value) -> anyhow::Result> { + let conf = serde_yaml::from_value::(config)?; + Ok(Arc::new(File { + content: conf + .content + .or(conf + .path + .map(|p| Ok::<_, ServiceError>(read_to_string(p)?)) + .transpose()?) + .unwrap_or_default(), + r#type: conf.r#type.unwrap_or("text/html".to_string()), // TODO infer mime from ext + })) + } +} + +impl Node for File { + fn handle<'a>( + &'a self, + _context: &'a mut NodeContext, + _request: NodeRequest, + ) -> Pin> + Send + Sync + 'a>> { + Box::pin(async move { + let mut r = Response::new(BoxBody::<_, ServiceError>::new( + self.content.clone().map_err(|_| unreachable!()), + )); + r.headers_mut() + .insert(CONTENT_TYPE, HeaderValue::from_str(&self.r#type).unwrap()); + Ok(r) + }) + } +} -- cgit v1.2.3-70-g09d2