使用字符串形成 HTTP 响应

Forming a HTTP response with strings

本文关键字:HTTP 响应 字符串      更新时间:2023-10-16

我正在开发带有boost的HTTP服务器,我对形成HTTP响应有一些疑问,尤其是标头。

以下是组装 GET 响应的代码:

std::string h = statusCodes[200]; // The status code is already finished with a 'rn'                                                                                  
std::string t = "Date: " + daytime_() + "rn";                                                                         
std::string s = "Server: Muffin 1.0rn";                                                                               
std::string content = search->second();                                                                                 
std::string type = "Content-Type: text/htmlrn";                                                                       
std::string length = "Content-Length: " + std::to_string(content.size()) + "rn";                                      
res = h + t + s + length + type + "rn" + content + "rn";     

正如他们在这个网站上所说的那样,这是标题规范:

请求和响应消息的格式相似,并且 以英语为导向。这两种消息都包含:

  • 首行,零行或多个标题行,
  • 一个空行(即 CRLF 本身),
  • 和可选的消息正文(例如文件、查询数据或查询输出)。

但是当我在服务器上执行请求时,只有日期在标题中,其余的直接在内容中

HTTP/1.1 200 OK                 // Header
Date: Tue May 24 10:28:58 2016  // Header
Server: Muffin 1.0              // Content
Content-Length: 31
Content-Type: text/html
This is supposed to be an ID

我不知道这有什么问题,这是我第一次处理HTTP响应。

感谢您的帮助

我终于找到了这个错误。

我的白天函数返回一个带有换行符的字符串。

这是原始函数,它使用折旧 ctime

std::string
Response::daytime_()
{
    std::time_t now = std::time(0);
    return std::ctime(&now);
}

现在带有 strftime 的新功能

std::string
Response::daytime_()
{
    time_t rawtime;
    struct tm * timeinfo;
    char buffer[80];
    time (&rawtime);
    timeinfo = localtime(&rawtime);
    strftime(buffer,80,"%a %b %d %H:%M:%S %Y",timeinfo);
    std::string time(buffer);
    return time;
}

以及形成响应的新方法,仅使用""

std::string res = "";
std::string h = statusCodes[200];
std::string t = "Date: " + daytime_() + "rn";
std::string s = "Server: Muffin 1.0rn";
std::string content = search->second();
std::string type = "Content-Type: text/htmlrn";
std::string length = "Content-Length: " + std::to_string(content.size()) + "rn";
res = h + t + s + length + type + "n" + content + "rn";