Paozhu logo Paozhu Docs
教程目录
START

Hello World

一行注解注册路由,一个函数返回响应。

新建控制器

在 controller/src/myhello.cpp 写入下面的函数。controller/include/myhello.h 由 CMake 配置阶段自动生成,不需要手写。构建时 paozhu_pre 会扫描注解,把路由写进 common/autocontrolmethod.hpp。

controller/src/myhello.cppcpp
#include "httppeer.h"
#include "myhello.h"

namespace http
{
//@urlpath(null,myhello)
asio::awaitable<std::string> myhello(std::shared_ptr<httppeer> peer)
{
    peer->output = "Hello from myhello!";
    co_return "";
}
}

重新编译、启动,然后访问 http://127.0.0.1/myhello,页面上会显示 Hello from myhello!。仓库自带的真实示例是 controller/src/testhello.cpp,对应路由 /hello。

注解怎么写

annotation formattext
//@urlpath(pre_filter, /path/:param):maskcode(1234):ratelimit(20,5):title("Page title")

// pre_filter  -> function name, or null for none
// /path/:param -> route; :param must be trailing
// maskcode(n) -> RBAC mask, 0 means the auth hook is skipped
// ratelimit(n,s) -> per-route rate limit
// title(...)   -> shown in the permission catalogue
片段作用示例
null没有前置过滤器//@urlpath(null,hello)
过滤器名先执行该函数,返回 @ok 放行admin_islogin
:maskcodeRBAC 权限掩码;0 表示不进权限钩子:maskcode(64)
:ratelimit路由级限速:ratelimit(20,5)
:title权限目录展示名:title("文章列表")

协程写法与同步写法

推荐返回 asio::awaitable<std::string>,在需要异步 ORM / HTTP 客户端时可以 co_await。同步函数返回 std::string 也完全可用,仓库里的压力测试路由就是同步写法。

controller/src/hello_sync.cppcpp
//@urlpath(null,hello/sync)
std::string hello_sync(std::shared_ptr<httppeer> peer)
{
    httppeer &client = peer->get_peer();
    client << "Hello from a sync handler";
    return "";
}

读取路径参数

controller/src/user_info.cppcpp
//@urlpath(null,user/info/:userid)
std::string user_info(std::shared_ptr<httppeer> peer)
{
    httppeer &client = peer->get_peer();
    client << "userid: " << client.get["userid"].to_string();
    return "";
}

访问 /user/info/42 时,client.get["userid"] 的值是 42。查询串参数同样从 client.get 读取,POST 表单从 client.post 读取。

四种常见输出

目标写法
纯文本 / HTMLpeer->output = "..."; 或 client << "..."
JSONclient.val["code"] = 0; client.out_json();
模板视图peer->view("cms/list");
跳转client.goto_url("/admin/main");