Files
42_INT_12_webserv/srcs/webserv/parsing_message_http.cpp
hugogogo 9a379c835d correction of trim in case of str only fill with delim char
+ added a new split, that also does trim, to split without counting newlines
2022-08-10 20:01:23 +02:00

98 lines
2.2 KiB
C++

#include "parsing_message_http.hpp"
/*
- parse_http_first_line() :
- copy first line into a vector of 3 strings
/ copy line into a vector of 3 strings
- parse_http_headers(std::string message)
-
- parse_http_body(std::string message)
*/
std::vector<std::string>
parse_http_first_line(std::string line)
{
std::vector<std::string> sline;
std::vector<std::string> line = "";
std::string sub;
std::string tmp;
size_t pos;
sline = ::split(line, ' ');
if (sline.size() == 3)
{
for (int i = 0; i < 3; i++)
{
tmp = sline[i];
tmp = ::trim(tmp, '\r');
tmp = ::trim(tmp, ' ');
line.push_back(tmp);
}
}
return line;
}
std::map<std::string, std::string>
parse_http_headers(std::string message)
{
std::map<std::string, std::string> headers;
std::vector<std::string> list;
std::vector<std::string>::iterator it;
std::string sub;
std::string key;
std::string val;
size_t pos;
pos = (message).find(CRLF CRLF);
sub = (message).substr(0, pos);
list = ::split(sub, '\n');
if ( maybe_http_first_line( *list.begin() ) )
list.erase(list.begin());
for (it = list.begin(); it != list.end(); it++)
{
// TODO: if pattern is not "NAME: value" return error
pos = (*it).find(':');
key = (*it).substr( 0, pos );
key = ::trim(key, ' ');
key = ::trim(key, '\r');
key = ::str_tolower(key);
val = (*it).substr( pos + 1 );
val = ::trim(val, ' ');
val = ::trim(val, '\r');
headers.insert( std::pair<std::string, std::string>(key, val) );
}
return headers;
}
std::string
parse_http_body(std::string message)
{
std::string body;
size_t pos;
pos = message.find(CRLF CRLF);
pos += std::string(CRLF CRLF).size();
// TODO: copying just like that might fail in case of binary or images
body = message.substr(pos);
return body;
}
bool maybe_http_first_line(std::string str)
{
// method SP target SP version https://www.rfc-editor.org/rfc/rfc7230.html#section-3.1.1
// version SP status SP reason https://www.rfc-editor.org/rfc/rfc7230.html#section-3.1.2
std::vector<std::string> sline;
sline = ::split(str, ' ');
if (sline.size() != 3)
return false;
if (sline[0].find(':') != std::string::npos)
return false;
return true;
}