简单高效解析形如[scheme://]host[:port][path][?query][#fragment]的uri.
【头文件】
struct URI
{
std::string scheme; // protocol string(http/https/ftp/...)
std::string host; // host string(domain or ip)
ushort port; // port number
std::string path; // path string(e.g. /index.html)
std::string query; // query string(e.g. a=1&b=2)
std::string fragment; // additional identifying information
URI() { Clear(); }
void Clear()
{
scheme = "http"; // default "http"
host.clear(); // default ""
port = 0; // default 0
path = "/"; // default "/"
query.clear(); // default ""
fragment.clear(); // default ""
}
};
/// @brief 解析形如[scheme://]host[:port][path][?query][#fragment]的uri
/// @param[in] uristr 需要解析的uri串
/// @param[out] uri 解析结果
/// @return 解析成功返回true,否则返回false
/// @attention 解析失败时,出参未定义
bool ParseUri(const string& uristr, URI& uri);
【实现文件】
bool ParseUri(const string& uristr, URI& uri)
{
const char* begin = uristr.c_str();
const char* end = uristr.c_str() + uristr.size();
const char* ptr = begin;
uri.Clear();
parse_host:
char c = 0;
while ((c = *ptr) != 0 and c != '.' and c != ':')
++ptr;
if (0 == c)
return false;
if (':' == c) // find the scheme
{
// find "//" after ":"
if (end - ptr <= 3)
return false;
if (*(ptr + 1) != '/' or *(ptr + 2) != '/')
return false;
uri.scheme.assign(begin, ptr - begin);
begin = (ptr +&#