1个不稳定版本
0.1.2 | 2024年5月30日 |
---|---|
0.1.1 |
|
0.1.0 |
|
#759 in HTTP服务器
25KB
547 行
NOXP
🦀 NOXP是一个受golang的net/http包启发的简单的Rust Web框架
NOXP仅使用标准库
🚧 下一步是什么
- 可选的多线程
- 将请求用于一些有用的目的
- 更好的路由系统
- 更多状态码
- 更多HTTP方法
- 头信息!
- 使用查询字符串
- 添加中间件
- 身份验证(自行实现!)
- 添加文档
- 发布到crates.io
使用方法
use std::fmt;
use noxp::Server;
use noxp::http::{ Response, Request, StatusCode };
struct Person {
name: String,
age: i32,
}
impl fmt::Display for Person {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{{ \"name\": \"{}\", \"age\": {} }}", self.name, self.age)
}
}
fn main() -> std::io::Result<()> {
// define the size of the thread pool
let size: usize = 4;
// create the server with a thread pool of defined size 4 (it's optional)
// it's also possible to use Server::default().set_pool(4)
let mut server = Server::default().set_pool(size);
// pay attention for the tuple (Method, &str)
server.handle_func(("GET", "/"), index);
server.handle_func(("POST", "/"), post);
// you can also send html (only in the views folder)
server.handle_func(("GET", "/hello"), file);
// and send json (only structs which implement Display)
server.handle_func(("GET", "/person"), json);
// listening at localhost:8080
server.listen_and_serve(8080)
}
fn index(_req: Request, res: Response) -> Response {
res.set_status(StatusCode::OK)
.set_text("Hello, World!")
}
fn post(req: Request, res: Response) -> Response {
req.print_body();
res.set_status(StatusCode::OK).set_json(req.get_body())
}
fn file(_req: Request, res: Response) -> Response {
res.set_status(StatusCode::OK).set_html("hello.html")
}
fn json(_req: Request, res: Response) -> Response {
let person = Person {
name: String::from("Menezes"),
age: 15,
};
res.set_status(StatusCode::OK).set_json(person)
}