#http-server #http #server #web

speed-rs-core

Rust 中核心的 HTTP 处理服务器库,提供底层的 HTTP 服务器实现

1 个不稳定版本

0.4.1 2023年11月27日
0.4.0 2023年11月25日
0.3.0 2023年11月24日
0.2.0 2023年11月20日
0.1.0 2023年11月20日

Web编程 中排名 2039

MIT 许可证

27KB
432

speed-rs-core

Rust 的核心 HTTP 服务器实现。

安装

使用 cargo 创建一个新的Rust项目

cargo new your-project

将包添加到您的项目中

cargo add speed-rs-core

或者在您的 Cargo.toml 文件的依赖关系中添加以下行

[dependencies]
...
speed-rs-core = "0.4.1"

最后构建项目

cargo build

现在您可以自由使用此包了。

如何使用

speed-rs-core 只提供核心 HTTP 处理,因此您需要处理更高级的抽象。以下是一个示例,说明如何在接收到请求时向客户端响应 HTML 文件

use std::fs;
use speed_rs_core::{HttpServer, HttpServerMode, HttpStatusStruct};

fn main() {
    // Create the server in single-thread mode
    let mut server = HttpServer::new(HttpServerMode::SingleThread, "127.0.0.1:3000");
    
    // Provide the request handling function
    server.insert_handler(|mut req, mut res| {
        res.set_status(HttpStatusStruct(200, "OK"));
        res.insert_header("Content-Type".to_string(), "text/html".to_string());


        // Read the HTML
        let err = match fs::read_to_string("public/index.html") {
            Ok(html) => {
                res.text(html);
                None
            },
            Err(e) => Some(e)
        };

        // Since the ownership of req and res are taken, you must return them back to the server
        if let Some(e) = err { Err((req, res, Box::new(e))) } else { Ok((req, res)) }
    });

    // Start listening for requests
    server.listen(|| {
        println!("Server is listening at http://127.0.0.1:3000");
    });
}

[!NOTE] 更多详情,您可以查看这个 指南

开发指南

为了进一步开发此包并利用 Rust 的强大功能,您可以实现像 RequestParamsExtractor 这样的 trait 以提供额外的功能

use std::collections::HashMap;
use speed_rs_core::HttpRequest;

trait RequestParamsExtractor {
    fn params(&self) -> HashMap<String, String>;
}

impl RequestParamsExtractor for HttpRequest {
    fn params(&self) -> HashMap<String, String> {
        // Implementation code here
        HashMap::new()
    }
}

// In your server's request handler
server.insert_handler(|mut req, mut res| {
    // ...
    let params = req.params();
    // ...
    Ok((req, res))
});

许可证

MIT 许可证 下分发。有关更多信息,请参阅 LICENSE

依赖项

~225KB