]> git.tdb.fi Git - libs/net.git/blob - source/http/request.cpp
Use string::size_type to store string offsets
[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         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         vector<string> parts = split(str.substr(0, lf-(str[lf-1]=='\r')), ' ', 2);
32         if(parts.size()<3)
33                 throw invalid_argument("Request::parse");
34
35         Request result(parts[0], parts[1]);
36         result.http_version = parse_version(parts[2]);
37
38         lf += result.parse_headers(str.substr(lf+1));
39
40         result.parse_content(str.substr(lf+1));
41
42         return result;
43 }
44
45 Request Request::from_url(const string &str)
46 {
47         Url url = parse_url(str);
48         if(url.scheme!="http")
49                 throw invalid_argument("Request::from_url");
50
51         string path = urlencode(url.path);
52         if(path.empty())
53                 path = "/";
54         if(!url.query.empty())
55         {
56                 path += '?';
57                 path += url.query;
58         }
59
60         Request result("GET", path);
61         result.set_header("Host", url.host);
62         result.set_header("Connection", "close");
63
64         return result;
65 }
66
67 } // namespace Http
68 } // namespace Msp