]> git.tdb.fi Git - libs/net.git/blob - source/http/request.cpp
Add a dynamic receiver class for more flexible packet handling
[libs/net.git] / source / http / request.cpp
1 #include "request.h"
2 #include <msp/strings/format.h>
3 #include <msp/strings/regex.h>
4 #include <msp/strings/utils.h>
5 #include "utils.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace Http {
11
12 Request::Request(const string &m, const string &p):
13         method(m),
14         path(p)
15 {
16         if(path.find(' ')!=string::npos)
17                 throw invalid_argument("Request::Request");
18 }
19
20 string Request::str() const
21 {
22         string result = format("%s %s %s\r\n", method, path, version_str(http_version));
23         result += str_common();
24
25         return result;
26 }
27
28 Request Request::parse(const string &str)
29 {
30         string::size_type lf = str.find('\n');
31         if(lf==0)
32                 throw invalid_argument("Request::parse");
33         vector<string> parts = split(str.substr(0, lf-(str[lf-1]=='\r')), ' ', 2);
34         if(parts.size()<3)
35                 throw invalid_argument("Request::parse");
36
37         Request result(parts[0], parts[1]);
38         result.http_version = parse_version(parts[2]);
39
40         lf += result.parse_headers(str.substr(lf+1));
41
42         result.parse_content(str.substr(lf+1));
43
44         return result;
45 }
46
47 Request Request::from_url(const string &str)
48 {
49         Url url = parse_url(str);
50         if(url.scheme!="http")
51                 throw invalid_argument("Request::from_url");
52
53         string path = urlencode(url.path);
54         if(path.empty())
55                 path = "/";
56         append(path, "?", url.query);
57
58         Request result("GET", path);
59         result.set_header("Host", url.host);
60         result.set_header("Connection", "close");
61
62         return result;
63 }
64
65 } // namespace Http
66 } // namespace Msp