Add the mutex protection for http response

This commit is contained in:
antao 2018-12-30 20:56:52 +08:00
parent d8c932218a
commit b0dd2d4b75
2 changed files with 18 additions and 12 deletions

View File

@ -360,16 +360,20 @@ void HttpResponseImpl::makeHeaderString(MsgBuffer *output) const
void HttpResponseImpl::appendToBuffer(MsgBuffer *output) const
{
if (_expriedTime >= 0 && _httpString && _datePos != std::string::npos)
if (_expriedTime >= 0)
{
bool isDateChanged = false;
auto newDate = getHttpFullDate(trantor::Date::now(), &isDateChanged);
if(isDateChanged)
std::lock_guard<std::mutex> lock(*_httpStringMutex);
if (_httpString && _datePos != std::string::npos)
{
memcpy(_httpString->data() + _datePos, newDate, strlen(newDate));
bool isDateChanged = false;
auto newDate = getHttpFullDate(trantor::Date::now(), &isDateChanged);
if (isDateChanged)
{
memcpy(_httpString->data() + _datePos, newDate, strlen(newDate));
}
output->append(*_httpString);
return;
}
output->append(*_httpString);
return;
}
if (!_fullHeaderString)
{
@ -392,10 +396,7 @@ void HttpResponseImpl::appendToBuffer(MsgBuffer *output) const
//output Date header
output->append("Date: ");
if (_expriedTime >= 0)
{
_datePos = output->readableBytes();
}
auto datePos = output->readableBytes();
output->append(getHttpFullDate(trantor::Date::date()));
output->append("\r\n\r\n");
@ -403,6 +404,8 @@ void HttpResponseImpl::appendToBuffer(MsgBuffer *output) const
output->append(*_bodyPtr);
if (_expriedTime >= 0)
{
std::lock_guard<std::mutex> lock(*_httpStringMutex);
_datePos = datePos;
_httpString = std::make_shared<std::string>(output->peek(), output->readableBytes());
}
}

View File

@ -22,6 +22,7 @@
#include <map>
#include <string>
#include <memory>
#include <mutex>
using namespace trantor;
namespace drogon
@ -36,7 +37,8 @@ class HttpResponseImpl : public HttpResponse
_closeConnection(false),
_left_body_length(0),
_current_chunk_length(0),
_bodyPtr(new std::string())
_bodyPtr(new std::string()),
_httpStringMutex(new std::mutex())
{
}
virtual HttpStatusCode statusCode() override
@ -325,6 +327,7 @@ class HttpResponseImpl : public HttpResponse
std::shared_ptr<std::string> _fullHeaderString;
mutable std::shared_ptr<std::string> _httpString;
mutable std::shared_ptr<std::mutex> _httpStringMutex;
mutable std::string::size_type _datePos = std::string::npos;
//trantor::Date receiveTime_;