From d95bcc094d5102cbc1b625b69bf6378e3fb730a8 Mon Sep 17 00:00:00 2001 From: Richard Walters Date: Wed, 4 Jul 2018 19:05:06 -0700 Subject: Add capability of setting other elements * userinfo * port (hasPort) * path * fragment Also include these element when generating string from URI. --- src/Uri.cpp | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 70 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/Uri.cpp b/src/Uri.cpp index 5d36a9d..eee40ad 100644 --- a/src/Uri.cpp +++ b/src/Uri.cpp @@ -555,6 +555,24 @@ namespace Uri { // Methods + /** + * This method returns an indication of whether or not + * the URI includes any element that is part of the + * authority of the URI. + * + * @return + * An indication of whether or not the URI includes + * any element that is part of the authority of the + * URI is returned. + */ + bool HasAuthority() const { + return ( + !host.empty() + || !userInfo.empty() + || hasPort + ); + } + /** * This method builds the internal path element sequence * by parsing it from the given path string. @@ -1249,30 +1267,77 @@ namespace Uri { impl_->scheme = scheme; } + void Uri::SetUserInfo(const std::string& userinfo) { + impl_->userInfo = userinfo; + } + void Uri::SetHost(const std::string& host) { impl_->host = host; } + void Uri::SetPort(uint16_t port) { + impl_->port = port; + impl_->hasPort = true; + } + + void Uri::ClearPort() { + impl_->hasPort = false; + } + + void Uri::SetPath(const std::vector< std::string >& path) { + impl_->path = path; + } + void Uri::SetQuery(const std::string& query) { impl_->query = query; } + void Uri::SetFragment(const std::string& fragment) { + impl_->fragment = fragment; + } + std::string Uri::GenerateString() const { std::ostringstream buffer; if (!impl_->scheme.empty()) { buffer << impl_->scheme << ':'; } - if (!impl_->host.empty()) { + if (impl_->HasAuthority()) { buffer << "//"; - if (ValidateIpv6Address(impl_->host)) { - buffer << '[' << impl_->host << ']'; - } else { - buffer << impl_->host; + if (!impl_->userInfo.empty()) { + buffer << impl_->userInfo << '@'; + } + if (!impl_->host.empty()) { + if (ValidateIpv6Address(impl_->host)) { + buffer << '[' << impl_->host << ']'; + } else { + buffer << impl_->host; + } } + if (impl_->hasPort) { + buffer << ':' << impl_->port; + } + } + // Special case: absolute but otherwise empty path. + if ( + impl_->IsPathAbsolute() + && (impl_->path.size() == 1) + ) { + buffer << '/'; + } + size_t i = 0; + for (const auto& segment: impl_->path) { + buffer << segment; + if (i + 1 < impl_->path.size()) { + buffer << '/'; + } + ++i; } if (!impl_->query.empty()) { buffer << '?' << impl_->query; } + if (!impl_->fragment.empty()) { + buffer << '#' << impl_->fragment; + } return buffer.str(); } } -- cgit v1.2.3