Paozhu logoPaozhu Docs
教程目录
DEV

控制器开发

注解路由、参数读取、Session/Cookie、响应输出与前置过滤器。

最小控制器

控制器放在 controller/src/,函数位于 namespace http 中。头文件由构建流程生成,不要手写。

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)
{
    httppeer &client = peer->get_peer();
    std::string name = client.get["name"].as_string("world");
    client.output = "Hello, " + name;
    co_return "";
}
}

参数与默认值

查询串与 POST 字段分别读取 client.get 和 client.post。to_string() 与 to_int() 不带参数;需要默认值时使用 as_string(default) / as_int(default)。

controller/src/session_demo.cppcpp
client.session["adminid"] = 10001;
client.save_session();
std::string sid = client.get_session_id();

client.set_cookie("token", "abc", 7200, "/", client.host, true, true, "Lax");
int uid = client.session["adminid"].to_int();
client.clear_session();

Session 修改后必须显式调用 save_session()。Cookie 完整参数为 set_cookie(name, value, expire, path, domain, httpOnly, secure, sameSite)。

前置过滤器

controller/src/admin_panel.cppcpp
//@urlpath(admin_islogin,admin/panel)
std::string admin_panel(std::shared_ptr<httppeer> peer)
{
    httppeer &client = peer->get_peer();
    client << "Admin panel";
    return "";
}

std::string admin_islogin(std::shared_ptr<httppeer> peer)
{
    httppeer &client = peer->get_peer();
    if (client.session["adminid"].to_int() == 0) return "admin/login";
    return "@ok";   // not "ok"
}