]> git.tdb.fi Git - libs/net.git/blob - source/http/request.cpp
01948592ef9c8033119bf86bfbf1ff40c66307f7
[libs/net.git] / source / http / request.cpp
1 #include <msp/strings/format.h>
2 #include <msp/strings/regex.h>
3 #include <msp/strings/utils.h>
4 #include "request.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
17 string Request::str() const
18 {
19         string result = format("%s %s %s\r\n", method, path, version_str(http_version));
20         result += str_common();
21
22         return result;
23 }
24
25 Request Request::parse(const string &str)
26 {
27         unsigned lf = str.find('\n');
28         vector<string> parts = split(str.substr(0, lf-(str[lf-1]=='\r')), ' ', 2);
29         if(parts.size()<3)
30                 throw invalid_argument("Request::parse");
31
32         Request result(parts[0], parts[1]);
33         result.http_version = parse_version(parts[2]);
34
35         lf += result.parse_headers(str.substr(lf+1));
36
37         result.parse_content(str.substr(lf+1));
38
39         return result;
40 }
41
42 Request Request::from_url(const string &str)
43 {
44         Url url = parse_url(str);
45         if(url.scheme!="http")
46                 throw invalid_argument("Request::from_url");
47
48         string path = url.path;
49         if(path.empty())
50                 path = "/";
51         if(!url.query.empty())
52         {
53                 path += '?';
54                 path += url.query;
55         }
56
57         Request result("GET", path);
58         result.set_header("Host", url.host);
59         result.set_header("Connection", "close");
60
61         return result;
62 }
63
64 } // namespace Http
65 } // namespace Msp