HttpParser: Add Reset() function (#1210)

This allows reuse of the HttpParser object for multiple requests.
This commit is contained in:
Peter Johnson
2018-07-22 19:41:23 -07:00
committed by GitHub
parent 794403dcea
commit c25d48fd0c
3 changed files with 39 additions and 0 deletions

View File

@@ -162,3 +162,15 @@ HttpParser::HttpParser(Type type) {
return self.m_aborted;
};
}
void HttpParser::Reset(Type type) {
http_parser_init(&m_parser,
static_cast<http_parser_type>(static_cast<int>(type)));
m_parser.data = this;
m_maxLength = 1024;
m_state = kStart;
m_urlBuf.clear();
m_fieldBuf.clear();
m_valueBuf.clear();
m_aborted = false;
}

View File

@@ -36,8 +36,19 @@ class HttpParser {
*/
static uint32_t GetParserVersion();
/**
* Constructor.
* @param type Type of parser (request or response or both)
*/
explicit HttpParser(Type type);
/**
* Reset the parser to initial state.
* This allows reusing the same parser object from request to request.
* @param type Type of parser (request or response or both)
*/
void Reset(Type type);
/**
* Set the maximum accepted length for URLs, field names, and field values.
* The default is 1024.

View File

@@ -190,4 +190,20 @@ TEST(HttpParserTest, HeadersCompleteUpgrade) {
ASSERT_FALSE(p.HasError());
}
TEST(HttpParserTest, Reset) {
HttpParser p{HttpParser::kRequest};
int callbacks = 0;
p.headersComplete.connect([&](bool) { ++callbacks; });
p.Execute("GET / HTTP/1.1\r\n");
ASSERT_EQ(callbacks, 0);
p.Execute("\r\n");
ASSERT_EQ(callbacks, 1);
p.Reset(HttpParser::kRequest);
p.Execute("GET / HTTP/1.1\r\n");
ASSERT_EQ(callbacks, 1);
p.Execute("\r\n");
ASSERT_EQ(callbacks, 2);
ASSERT_FALSE(p.HasError());
}
} // namespace wpi