]> git.tdb.fi Git - libs/net.git/blobdiff - source/request.cpp
Add functions for parsing and building URIs and query strings
[libs/net.git] / source / request.cpp
index e63dc66f7487e08803380a6f82755528733c52ab..6bad3700681fefdffd40178a88e44cb146442e0b 100644 (file)
@@ -9,6 +9,7 @@ Distributed under the LGPL
 #include <msp/strings/regex.h>
 #include <msp/strings/utils.h>
 #include "request.h"
+#include "utils.h"
 
 using namespace std;
 
@@ -28,26 +29,42 @@ string Request::str() const
        return result;
 }
 
-Request Request::from_url(const string &url)
+Request Request::parse(const string &str)
 {
-       if(RegMatch match=Regex("^http://([a-zA-Z0-9.-]+)(:([0-9]+))?(/[^ #]*)?$").match(url))
+       unsigned lf=str.find('\n');
+       vector<string> parts=split(str.substr(0, lf-(str[lf-1]=='\r')), ' ', 2);
+       if(parts.size()<3)
+               throw InvalidParameterValue("Invalid request");
+
+       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 InvalidParameterValue("Only http scheme is supported");
+       string path=url.path;
+       if(path.empty())
+               path="/";
+       if(!url.query.empty())
        {
-               string host=match[1].str;
-               string port="80";
-               if(match[3])
-                       port=match[3].str;
-               string path=match[4].str;
-               if(path.empty())
-                       path="/";
-
-               Request result("GET", path);
-               result.set_header("host", host);
-               result.set_header("x-port", port);
-
-               return result;
+               path+='?';
+               path+=url.query;
        }
-       else
-               throw InvalidParameterValue("Invalid URL");
+
+       Request result("GET", path);
+       result.set_header("Host", url.host);
+       result.set_header("Connection", "close");
+
+       return result;
 }
 
 } // namespace Http