1 个不稳定发布
0.0.0 | 2023年1月16日 |
---|
#96 in #server-framework
5KB
aoi - 预开发草案
aoi - [葵] 日本流行植物的名字 - 是 基于struct的Web框架。
这是一个预开发草案。
特性
- 基于struct的架构,其中服务器是一个struct
- 积极使用 宏
示例(计划中)
简单服务器
#[server]
MyServer {
#[GET /]
{
self.OK("Hello!")
}
}
#[main]
{
let my_server = MyServer;
bloom!(":3000", my_server)
}
$ curl https://127.0.0.1:3000
Hello!
处理数据库、路径参数、请求体
struct User {
id: u64,
name: String,
}
struct CreateUser {
name: String,
password: String,
}
#[server]
UserServer {
conn: ConnectionPool<Postgres>,
} {
#[GET /api/users/{id:u64}]
{
let user = SQL![
SELECT id, name FROM users
WHERE id = $id
; as User]
.fetch_one(&self.conn)
.await?;
self.OK(user)
}
#[POST /api/users, body: CreateUser]
{
let CreateUser { name, password } = body;
let created_user = SQL![
INSERT INTO users (name, password) VALUES ($name, $password)
RETURNING id, name
; as User]
.fetch_one(&self.conn)
.await?;
self.Created(created_user)
}
}
#[main]
{
let connection_pool = PgPoolOptions::new()
.max_connections(5)
.connect(
"postgres://postgres:password@localhost/test"
).await?;
let user_server = UserServer {
conn: connection_pool,
};
bloom!(":8080", user_server)
}
嵌套服务器
struct CreateUser {
name: String,
password: String,
}
#[server]
RootServer {
#[GET /]
{
self.OK("Hello!")
}
#[GET /health_check]
{
self.NoContent()
}
}
#[server]
UserServer {
conn: ConnectionPool<Postgres>,
} {
#[GET /{id:u64}]
{
let user = SQL![
SELECT id, name FROM users
WHERE id = $id
; as User]
.fetch_one(&self.conn)
.await?;
self.OK(user)
}
#[POST /, body: CreateUser]
{
let CreateUser { name, password } = body;
let created_user = SQL![
INSERT INTO users (name, password) VALUES ($name, $password)
RETURNING id, name
; as User]
.fetch_one(&self.conn)
.await?;
self.Created(created_user)
}
}
#[main]
{
let connection_pool = PgPoolOptions::new()
.max_connections(5)
.connect(
"postgres://postgres:password@localhost/test"
).await?;
let user_server = UserServer {
conn: connection_pool,
};
let root_server = RootServer;
bloom!(":8080",
/api/users => user_server,
/ => root_server
)
}
依赖项
~1.5MB
~35K SLoC