Browse Source

Add merge to URL (can merge absolute paths with relative paths)

pull/2/head
Nubben 5 years ago
parent
commit
f68e8f65c9
  1. 48
      src/URL.cpp
  2. 9
      src/URL.h

48
src/URL.cpp

@ -2,21 +2,55 @@ @@ -2,21 +2,55 @@
#include "StringUtils.h"
URL::URL() {
protocol = "";
host = "";
document = "";
}
URL::URL(std::string const& url) {
construct(url);
}
std::string URL::toString() {
std::string URL::toString() const {
if (isRelative()) {
return document;
}
return protocol + "://" + host + document;
}
bool URL::isRelative() {
bool URL::isRelative() const {
return protocol.size() == 0;
}
URL URL::merge(URL const& url) const {
if (!url.isRelative()) {
return url.copy();
}
URL returnURL = copy();
if (url.document[0] == '/' && url.document[1] == '/') {
auto slashPos = url.document.find('/', 2);
returnURL.host = url.document.substr(2, slashPos - 2);
if (slashPos == std::string::npos) {
returnURL.document = "/";
} else {
returnURL.document = url.document.substr(slashPos);
}
} else if (url.document[0] == '/') {
returnURL.document = url.document;
} else {
if (returnURL.document.back() != '/') {
auto finalSlashPos = returnURL.document.find_last_of('/');
returnURL.document.erase(finalSlashPos + 1);
}
returnURL.document += url.document;
}
return returnURL;
}
void URL::construct(std::string const& url) {
protocol = getProtocolFromURL(url);
if (protocol.size() != 0) {
@ -33,7 +67,15 @@ void URL::construct(std::string const& url) { @@ -33,7 +67,15 @@ void URL::construct(std::string const& url) {
}
std::ostream& operator<<(std::ostream& out, URL& url) {
URL URL::copy() const {
URL url;
url.protocol = protocol;
url.host = host;
url.document = document;
return url;
}
std::ostream& operator<<(std::ostream& out, URL const& url) {
out << url.toString();
return out;
}

9
src/URL.h

@ -5,10 +5,12 @@ @@ -5,10 +5,12 @@
#include <iostream>
struct URL {
URL();
URL(std::string const& url);
std::string toString();
bool isRelative();
std::string toString() const;
bool isRelative() const;
URL merge(URL const& url) const;
std::string protocol;
std::string host;
@ -16,8 +18,9 @@ struct URL { @@ -16,8 +18,9 @@ struct URL {
private:
void construct(std::string const& url);
URL copy() const;
};
std::ostream& operator<<(std::ostream& out, URL& url);
std::ostream& operator<<(std::ostream& out, URL const& url);
#endif

Loading…
Cancel
Save