]> git.tdb.fi Git - libs/net.git/blob - source/request.cpp
Add Server class
[libs/net.git] / source / request.cpp
1 /* $Id$
2
3 This file is part of libmsphttp
4 Copyright © 2008  Mikkosoft Productions, Mikko Rasa
5 Distributed under the LGPL
6 */
7
8 #include <msp/strings/formatter.h>
9 #include <msp/strings/regex.h>
10 #include <msp/strings/utils.h>
11 #include "request.h"
12
13 using namespace std;
14
15 namespace Msp {
16 namespace Http {
17
18 Request::Request(const string &m, const string &p):
19         method(m),
20         path(p)
21 { }
22
23 string Request::str() const
24 {
25         string result=format("%s %s %s\r\n", method, path, version_str(http_version));
26         result+=str_common();
27
28         return result;
29 }
30
31 Request Request::parse(const string &str)
32 {
33         unsigned lf=str.find('\n');
34         vector<string> parts=split(str.substr(0, lf-(str[lf-1]=='\r')), ' ', 2);
35         if(parts.size()<3)
36                 throw InvalidParameterValue("Invalid request");
37
38         Request result(parts[0], parts[1]);
39         result.http_version=parse_version(parts[2]);
40
41         lf+=result.parse_headers(str.substr(lf+1));
42
43         result.parse_content(str.substr(lf+1));
44
45         return result;
46 }
47
48 Request Request::from_url(const string &url)
49 {
50         if(RegMatch match=Regex("^http://([a-zA-Z0-9.-]+(:[0-9]+)?)(/[^ #]*)?$").match(url))
51         {
52                 string host=match[1].str;
53                 string path=match[3].str;
54                 if(path.empty())
55                         path="/";
56
57                 Request result("GET", path);
58                 result.set_header("Host", host);
59                 result.set_header("Connection", "close");
60
61                 return result;
62         }
63         else
64                 throw InvalidParameterValue("Invalid URL");
65 }
66
67 } // namespace Http
68 } // namespace Msp