#pragma once #include #include #include /*! * \file */ /*! * \brief The Uri struct */ struct Uri { std::string scheme; ///< The URI scheme std::string username; ///< The URI username std::string password; ///< The URI password std::string host; ///< The URI host std::string port; ///< The URI port std::string query; ///< The URI query std::string hash; ///< The URI hash }; /*! * \brief parse_uri * \param str The string that contains a URI. * It must be a valid URI, this function will to do no validation. * There may be no leading or trailing whitespace * \return The corresponding URI struct. */ Uri parse_uri(std::string str) { std::string scheme = "(?:(.+?)://)?"; std::string uname_pass = "(?:(.*?)?(?::(.*?))@)?"; std::string host = "(.+?)"; std::string port = "(?::(\\d+?))?"; std::string query = "(?:\\?(.+?))?"; std::string hash = "(?:#(.+?))?"; std::regex expr("^" + scheme + uname_pass + host + port + query + hash + "$"); std::smatch matches; std::regex_match(str, matches, expr); return { matches[1].str(), matches[2].str(), matches[3].str(), matches[4].str(), matches[5].str(), matches[6].str(), matches[7].str() }; } /*! * \brief debug_uri Debug function to see the contents of the URI struct. * \param uri * \return A Debug string representation of an URI */ std::string debug_uri(Uri uri) { std::stringstream ss; ss << "scheme: " << uri.scheme << std::endl << "username: " << uri.username << std::endl << "password: " << uri.password << std::endl << "host: " << uri.host << std::endl << "port: " << uri.port << std::endl << "query: " << uri.query << std::endl << "hash: " << uri.hash << std::endl; return ss.str(); } /*! * \brief uri_to_string * \param uri * \return returns the string representation of the URI stored in uri. */ std::string uri_to_string(Uri uri) { return (!uri.scheme.empty() ? uri.scheme + "://" : "") + (!uri.username.empty() ? uri.username + (!uri.password.empty() ? ":" + uri.password : "") + "@" : "") + uri.host + (!uri.port.empty() ? ":" + uri.port : "") + (!uri.query.empty() ? "?" + uri.query : ""); }