1 个不稳定版本

0.7.0 2023年12月28日

#718文本处理

AGPL-3.0

21KB
252

rust-cgi

基于http类型,在Rust中轻松创建CGIfootnote:[复古!]footnote:[通用网关接口1.1,RFC 3875]程序footnote:[是的,我拼的是programme,这是正确的拼写方式.]。

crates.io released version badge crates.io released licencegpl

:toc

安装与使用

Cargo.toml:

[code,toml]

[dependencies]
cgi2 = "0.7"

在您的main函数上使用cgi::main宏,接受一个Request并返回一个Response

[code,rust]

#[cgi::main]
fn main(request: cgi::Request) -> cgi::Response {
     cgi::text_response(200, "Hello World")
}

如果您的函数返回一个Result,这同样有效。如果您的函数返回一个Result,错误将打印到stderr,并返回HTTP 500错误。

[code,rust]

#[cgi::main]
fn main(request: cgi::Request) -> Result<cgi::Response, String> {
    let greeting = std::fs::read_to_string("greeting.txt").map_err(|_| "Couldn't open file")?;

    Ok(cgi::text_response(200, greeting))
}

它将解析并提取CGI环境变量和HTTP请求正文以创建Request,调用您的函数以创建响应,并将您的Response转换为正确的格式并打印到stdout。如果此程序不是作为CGI调用(例如,缺少必需的环境变量),它将引发panic。

您也可以在main函数中直接调用cgi::handle函数

[code,rust]

fn main() { 
    cgi::handle(|request: cgi::Request| -> cgi::Response {
        cgi::html_response(200, "<html><body><h1>Hello World!</h1></body></html>")
    })
}

响应快捷方式

一些快捷方式可以轻松创建快捷方式

cgi:empty_response(status_code):: 不包含正文并带有该HTTP状态码的HTTP响应,例如return cgi::empty_response(404);以返回一个链接:HTTP 404 Not Foundcgi::html_response(status_code, text):: 将text转换为字节(UTF8),并以该status_code和HTML Content-Type头部发送。 cgi::string_response(status_code, text):: 将text转换为字节(UTF8),并以该status_code发送,例如return cgi::string_response(200, "Hello World!"):: 返回一个简单的纯文本响应. cgi::binary_response(status_code, blob):: 发送 blob`带有该状态码。

重新导出

http被重新导出(作为cgi::http)。

cgi::Response/Requesthttp::Response>>/Request<Vec<u8>>

本地运行

Python提供了一个简单的CGI网络服务器,您可以使用它来运行您的脚本。二进制文件必须位于一个cgi-bin目录中,因此您需要创建该目录并将二进制文件复制到其中。假设有一个名为example的项目,在项目根目录中运行此命令(即Cargo.toml所在的目录)

mkdir cgi-bin
cargo build --example hello_world
cp target/debug/examples/hello_world cgi-bin/hello_world
python3 -m http.server --cgi

然后打开链接:https://127.0.0.1:8000/cgi-bin/hello_world[]

另请参阅

使用此功能的内容

资源

为什么?

CGI已经过时,但易于部署。只需将二进制文件放入正确位置,Apache(或任何其他服务器)就会为其提供服务。Rust运行速度快,因此对于简单的事情,启动自定义HTTP服务器应该没有太多缺点。

版权

版权链接:请参阅文件LICENCE

依赖项

~2MB
~45K SLoC