]> git.tdb.fi Git - libs/net.git/blobdiff - source/http/request.cpp
Prepare for assimilation into mspnet
[libs/net.git] / source / http / request.cpp
diff --git a/source/http/request.cpp b/source/http/request.cpp
new file mode 100644 (file)
index 0000000..c948755
--- /dev/null
@@ -0,0 +1,65 @@
+#include <msp/strings/formatter.h>
+#include <msp/strings/regex.h>
+#include <msp/strings/utils.h>
+#include "request.h"
+#include "utils.h"
+
+using namespace std;
+
+namespace Msp {
+namespace Http {
+
+Request::Request(const string &m, const string &p):
+       method(m),
+       path(p)
+{ }
+
+string Request::str() const
+{
+       string result = format("%s %s %s\r\n", method, path, version_str(http_version));
+       result += str_common();
+
+       return result;
+}
+
+Request Request::parse(const string &str)
+{
+       unsigned lf = str.find('\n');
+       vector<string> parts = split(str.substr(0, lf-(str[lf-1]=='\r')), ' ', 2);
+       if(parts.size()<3)
+               throw invalid_argument("Request::parse");
+
+       Request result(parts[0], parts[1]);
+       result.http_version = parse_version(parts[2]);
+
+       lf += result.parse_headers(str.substr(lf+1));
+
+       result.parse_content(str.substr(lf+1));
+
+       return result;
+}
+
+Request Request::from_url(const string &str)
+{
+       Url url = parse_url(str);
+       if(url.scheme!="http")
+               throw invalid_argument("Request::from_url");
+
+       string path = url.path;
+       if(path.empty())
+               path = "/";
+       if(!url.query.empty())
+       {
+               path += '?';
+               path += url.query;
+       }
+
+       Request result("GET", path);
+       result.set_header("Host", url.host);
+       result.set_header("Connection", "close");
+
+       return result;
+}
+
+} // namespace Http
+} // namespace Msp