From 4c0942a78734d14acdb7ffbe276c3efee5257198 Mon Sep 17 00:00:00 2001 From: manageryzy Date: Wed, 21 Jun 2017 14:48:07 +0800 Subject: [PATCH] prase post data Signed-off-by: manageryzy --- server_http.hpp | 59 +++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/server_http.hpp b/server_http.hpp index ad2b65b9..b1dffc6f 100644 --- a/server_http.hpp +++ b/server_http.hpp @@ -858,8 +858,8 @@ namespace SimpleWeb { void response(int status) { - if (http_status_codes.find(status == http_status_codes.end())) - throw std::runtime_error("error status code: " + status); + if (http_status_codes.find(status) == http_status_codes.end()) + throw std::runtime_error("error status code: " + std::to_string(status)); this->status = status; } @@ -1034,6 +1034,61 @@ namespace SimpleWeb { return result; } + std::unordered_multimap parse_post() + { + std::unordered_multimap result; + + auto it = this->header.find("Content-Type"); + if (it == this->header.end()) return result; + + std::string type = it->second; + if(type == "application/x-www-form-urlencoded") + { + std::string cont = content.string(); + static regex::regex pattern("([\\w+%]+)=?([^&]*)"); + int submatches[] = { 1, 2 }; + auto it_begin = regex::sregex_token_iterator(cont.begin(), cont.end(), pattern, submatches); + auto it_end = regex::sregex_token_iterator(); + for (auto it = it_begin; it != it_end; ++it) { + auto submatch1 = it->str(); + auto submatch2 = url_decode((++it)->str()); + result.emplace(submatch1, submatch2); + } + } + else if(type == "application/json") + { + throw std::runtime_error("could not parse json data"); + } + else if(type == "application/xml") + { + throw std::runtime_error("could not parse xml data"); + } + else if(type.find("multipart/form-data")!=std::string::npos) + { + auto st = type.find("boundary="); + auto boundary = type.substr(st+9); + std::vector conts(std::istream_iterator(content), {}); + for(auto it =conts.begin();it < conts.end() ; ++it) + { + while(it->find("name") == std::string::npos) + { + ++it; + if (it == conts.end()) + return result; + } + auto name = it->substr(6,it->length() - 7); + ++it; + result.emplace(name, *it); + } + } + else + { + throw std::runtime_error("unknown type"); + } + + return result; + } + private: Request(const socket_type &socket): content(streambuf) { try {