Skip to content

Instantly share code, notes, and snippets.

@jimhansson
Last active June 29, 2017 22:02
Show Gist options
  • Save jimhansson/3e1ea7ed1b2fb68472b34785057638bb to your computer and use it in GitHub Desktop.
Save jimhansson/3e1ea7ed1b2fb68472b34785057638bb to your computer and use it in GitHub Desktop.
Simple URL thing
#include <boost/regex.hpp>
#include <tuple>
#include <string>
#include <iostream>
// Simple URL
// protocol, host, port, path, query
typedef std::tuple<std::string, std::string, int, std::string, std::string> URL;
// use them as accessors, not only getters;
auto protocol(const URL& url) -> std::string& { return std::get<0>(url); };
auto hostname(const URL& url) -> std::string& { return std::get<1>(url); };
auto port(const URL& url) -> int& { return std::get<2>(url); };
auto path(const URL& url) -> std::string& { return std::get<3>(url); };
auto query(const URL& url) -> std::string& { return std::get<4>(url); };
auto operator<<(std::ostream& os, const URL& url) -> std::ostream& {
return os << "[" << protocol(url) << "://" << hostname(url) << ":" << port(url) << path(url) << "?" << query(url) << "]";
}
// needs works for more protocol and tests
auto parseURL(std::string url) -> URL {
URL res;
boost::regex ex("(http|https)://([^/ :]+):?([^/ ]*)(/?[^ #?]*)\\x3f?([^ #]*)#?([^ ]*)");
boost::cmatch what;
auto default_for_protocol = [](std::string proto) -> int {
return 80;
};
if(regex_match(url.c_str(), what, ex)) {
/*
std::cout << "what: "
<< std::string(what[1].first, what[1].second) << " "
<< std::string(what[2].first, what[2].second) << " "
<< std::string(what[3].first, what[3].second) << " "
<< std::string(what[4].first, what[4].second) << " "
<< std::string(what[5].first, what[5].second) << std::endl;
*/
std::string port = std::string(what[3].first, what[3].second);
URL foo { std::string(what[1].first, what[1].second),
std::string(what[2].first, what[2].second),
port != "" ? std::stoi(port) : -1, // lexical_cast maybe
std::string(what[4].first, what[4].second),
std::string(what[5].first, what[5].second) };
return foo;
} else {
throw std::invalid_argument("url not correctly formated");
}
}
@jimhansson
Copy link
Author

try to remove the need for boost::regex

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment