Skip to content

HttpResponse的setBody方法bug #9

Description

@KivinChiu

Description / 描述

setBody方法,不应该附带header的ContentType设置,这样设计其实并不合理。两个重载函数都有默认值,导致习惯性编码(setStatus -> setHeader -> setBody -> return) 这套逻辑,setBody会覆盖前面的header设置。
这两个函数签名都带了默认的 text/plain:
void setBody(const std::string& body, const std::string& contentType = "text/plain");
void setBody(std::string&& body, const std::string& contentType = "text/plain");

甚至大佬你自己写的 OpenApiEndpoint.h 都受此影响(浏览器把返回都当做了普通文本)。以下是你的部分源码:
// JSON 端点
router.get(jsonPath,
[document](const HttpRequest&) -> HttpResponse
{
HttpResponse res;
res.setStatus(HttpStatusCode::hOk);
res.setHeader("Content-Type", "application/json; charset=utf-8");
// 不硬编码 CORS 头,遵循用户配置的 CORS 中间件策略
res.setBody(document->generateString()); ###### 此处函数默认值 text/plain 覆盖了上面的header
return res;
});

Steps to Reproduce / 复现步骤

运行 openapi_server 后访问 http://localhost:8080/openapi.json 结果以文本处理而非json

Expected Behavior / 期望行为

setBody不要改变header,或者第二个参数默认值为空字符串,只有当有值时才设置,否则保持不变

Platform / 平台

Linux (GCC)

Compiler Version / 编译器版本

No response

Boost Version / Boost 版本

No response

Build/Runtime Logs / 构建/运行日志

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugSomething isn't working

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions