< 返回版块

长琴 发表于 2024-05-13 07:34

Tags:rust,日报,goldbot,valitron,zeke,ufetch

[new lib] goldboot

Goldboot是一款为真实硬件构建机器镜像的工具,它可以实现接近不可变的基础设施,而无需大量额外的工作。

在 goldboot 方法中,可以为部署的每台计算机创建一个声明性配置文件。使用此配置,goldboot 会在本地计算机或 CI 平台(如 Github Actions)上构建映像。生成的映像可以通过 USB 驱动器或 PXE 启动部署到实际硬件。

GitHub: https://github.com/fossable/goldboot

[new ver] valitron v0.4.1

valitron是一个Rust 字段校验工具。

新版本更新如下:

  • 新增Email规则
  • 新增正则规则
  • 添加IP和URL规则示例
fn main() {
    let validator = Validator::new()
        .rule("name", Required.and(StartWith("hello")))
        .rule("age", custom(age_limit))
        .message([
            ("name.required", "name is required"),
            ("name.start_with", "name should be starts with `hello`"),
        ]);

    let person = Person {
        name: "li",
        age: 18,
    };

    let res = validator.validate(person);
    // or using trait
    let res = person.validate(validator);
}

fn age_limit(n: &mut u8) -> Result<(), Message> {
    if *n >= 25 && *n <= 45 {
        return Ok(());
    }
    Err("age should be between 25 and 45".into())
}

GitHub: https://github.com/tu6ge/valitron

[new lib] zeke

Zeke 是一个建立在 Tokio 之上的 HTTP 库,关注简单和极简主义。下面是一些示例:

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use zeke::http::{
    context::{get_context, set_context, Contextable}, 
    handler::Handler, 
    middleware::{Middleware, MiddlewareGroup}, 
    response::{new_response, set_header}, 
    router::{Route, Router},
};


#[tokio::main]
async fn main() {


    //================================================================
    // creating a router
    //================================================================

	let mut r = Router::new();

    //================================================================
    // creating a handler
    //================================================================

    pub fn handle_home() -> Handler {
        return Handler::new(|request| {
            let response = new_response(200, "<h1>Home</h1><a href='/about'>About</a>");
            let response = set_header(response, "Content-Type", "text/html");
            return (request, response);
        });
    }

    pub fn handle_about() -> Handler {
        return Handler::new(|request| {
            let response = new_response(200, "<h1>About</h1><a href='/'>Home</a>");
            let response = set_header(response, "Content-Type", "text/html");
            return (request, response);
        });
    }

    //================================================================
    // creating a type to represent shared state
    //================================================================

    pub enum AppContext {
        Trace,
    }

    impl Contextable for AppContext {
        fn key(&self) -> &'static str {
            match self {
                AppContext::Trace => {"TRACE"},
            }
        }
    }

    //================================================================
    // creating a middleware to track when our request starts
    //================================================================

    pub fn mw_trace() -> Middleware {
        return Middleware::new(|request| {
            let trace = HttpTrace{
                time_stamp: chrono::Utc::now().to_rfc3339(),
            };
            let trace_encoded = serde_json::to_string(&trace);
            match trace_encoded {
                Ok(trace_encoded) => {
                    set_context(request, AppContext::Trace, trace_encoded);
                    return None;
                },
                Err(_) => {
                    return Some(new_response(500, "failed to encode trace"));
                }
            }
        });
    }

    //================================================================
    // creating a middleware to log our request processing time
    //================================================================

    pub fn mw_trace_log() -> Middleware {
        return Middleware::new(|request| {
            let trace = get_context(&request.context, AppContext::Trace);
            if trace == "" {
                return Some(new_response(500, "trace not found"));
            }
            let trace: HttpTrace = serde_json::from_str(&trace).unwrap();
            let elapsed_time = trace.get_time_elapsed();
            let log_message = format!("[{}][{}][{}]", request.method, request.path, elapsed_time);
            println!("{}", log_message);
            return None;
        });
    }

    //================================================================
    // grouping middleware for reusability
    //================================================================

    pub fn mw_group_trace() -> MiddlewareGroup {
        return MiddlewareGroup::new(vec![mw_trace()], vec![mw_trace_log()]);
    }

    //================================================================
    // creating a type to track our request processing time
    //================================================================

    #[derive(Debug, Serialize, Deserialize)]
    pub struct HttpTrace {
        pub time_stamp: String,
    }

    impl HttpTrace {
        /// Prints the time elapsed since the `time_stamp` was set.
        pub fn get_time_elapsed(&self) -> String {
            if let Ok(time_set) = DateTime::parse_from_rfc3339(&self.time_stamp) {
                let time_set = time_set.with_timezone(&Utc);
                let now = Utc::now();
                let duration = now.signed_duration_since(time_set);
                let micros = duration.num_microseconds();
                match micros {
                    Some(micros) => {
                        if micros < 1000 {
                            return format!("{}µ", micros);
                        }
                    },
                    None => {

                    }
                }
                let millis = duration.num_milliseconds();
                return format!("{}ms", millis);
            } else {
                return "failed to parse time_stamp".to_string();
            }
        }
    }

    //================================================================
    // mounting handlers with middleware/outerware
    //================================================================

    // mount a handler with middleware/outerware
    r.add(Route::new("GET /", handle_home())
        .middleware(mw_trace())
        .outerware(mw_trace_log())
    );

    // mount a handler with a middleware group
    r.add(Route::new("GET /about", handle_about())
        .group(mw_group_trace())
    );

    //================================================================
    // starting the server
    //================================================================

    let err = r.serve("127.0.0.1:8080").await;
    match err {
        Some(e) => {
            println!("Error: {:?}", e);
        },
        None => {
            println!("Server closed");
        },
    }

}

GitHub: https://github.com/Phillip-England/zeke

[new lib] ufetch

一个简单的Linux系统消息获取工具。

$ ufetch

提供OS、Kernel、Host、Shell、Packages、CPU、GPU、Memory、Disk等信息。

GitHub: https://github.com/tyroruyk/ufetch


From 日报小组 长琴

社区学习交流平台订阅:

评论区

写评论

还没有评论

1 共 0 条评论, 1 页