3个版本
0.1.2 | 2023年8月26日 |
---|---|
0.1.1 | 2023年8月26日 |
#372 in 异步
每月下载量 68次
31KB
481 行
liteapi
概述
liteapi 是一个强大且易于使用的 litestorm 服务,用于创建 REST API。考虑到性能,liteapi 具有高度的多线程和异步特性,让您能够轻松构建快速且响应灵敏的 API。凭借其用户友好的界面和直观的设计,liteapi 使您能够轻松开始构建自己的 API。无论您是经验丰富的开发者还是初学者,liteapi 都提供了您创建强大且可扩展的 REST API 所需的工具。
功能
liteapi 通过必须返回一个带有给定枚举的 http-response 并将查询参数作为参数,为您提供了很多灵活性。这样做听起来有些多余,但通过这种方式,您可以为处理函数提供比其他框架更多的灵活性。让我们使用 liteapi 创建一个简单的 REST API,该 API 请求一个作为查询参数的 apikey(在生产环境中不要请求 apikey 作为查询参数)
use liteapi::{LiteAPI, http, entry, json, json2string};
entry! {
LiteAPI::new().await
.get("/", index).await
.run().await;
}
// Note that every handler has to take query-pairs as the one and only argument.
// Also note that the handler can't be asynchronous.
fn index(q: http::QueryParams) -> http::Response {
match q.get("apikey") {
None => {
http::Response::Plain(http::StatusCode::Forbidden.detail("Please provide an apikey!"))
},
Some(apikey) => {
let secret_apikey = "1234"; // Please dont do this in production
if apikey == secret_apikey {
let json = json!({"Hello, ": "World!"});
http::Response::Json(json2string(&json).unwrap())
// Also note that there is a json2string macro with which you can turn anything into json in liteapi
} else {
http::Response::Plain(http::StatusCode::Forbidden.detail("The apikey is wrong!"))
}
}
}
}
// That's it this api will wait for a request on the default path and give a Forbidden if the apikey is not provided or wrong
让我们为这个 REST API 添加另一个路由,这次我们将返回一些 HTML!
use liteapi::{LiteAPI, http, entry, html2string, json, json2string};
entry! {
LiteAPI::new().await
.get("/", index).await
.get("/template", template).await // Dont forget to add the route here
.run().await;
}
// Note that every handler has to take query-pairs as the one and only argument.
// Also note that the handler can't be asynchronous.
fn index(query: http::QueryParams) -> http::Response {
match query.get("apikey") {
None => {
http::Response::Plain(http::StatusCode::Forbidden.detail("Please provide an apikey!"))
},
Some(apikey) => {
let secret_apikey = "1234"; // Please dont do this in production
if apikey == secret_apikey {
let json = json!({"Hello, ": "World!"});
http::Response::Json(json2string(&json).unwrap())
// Also note that there is a json2string macro with which you can turn anything into json in liteapi
} else {
http::Response::Plain(http::StatusCode::Forbidden.detail("The apikey is wrong!"))
}
}
}
}
// Here you can see even though we are not working with the query-pairs we have to take them as an argument
fn template(_: http::QueryParams) -> http::Response {
let html = html2string(r"path\to\template.html").expect("Error reading the html!");
http::Response::Html(html)
}
// This was very easy right? Imagine the possibilities combining these two routes
以下是一些即将推出的更多功能
- 支持 http2.0 和 http3.0
- 支持 oauth2
- 支持 websockets
- 支持位置查询参数:localhost:7878/{id}/{name}/
依赖项
~1–1.7MB
~34K SLoC