-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathurl.cpp
More file actions
72 lines (61 loc) · 1.79 KB
/
url.cpp
File metadata and controls
72 lines (61 loc) · 1.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include "url.h"
#include "str.h"
#include <format>
using namespace std;
const string prot_end("://");
url::url(const std::string& abs_url) : abs_url{abs_url} {
string t = abs_url;
// protocol
size_t pidx = t.find(prot_end);
if(pidx != string::npos) {
protocol = t.substr(0, pidx);
if(pidx + prot_end.size() < t.size()) {
t = t.substr(pidx + prot_end.size());
}
}
// host
size_t hidx = t.find_first_of('/');
if(hidx == string::npos) {
host = t;
t = "";
} else {
host = t.substr(0, hidx);
t = t.substr(hidx);
}
// query
query = t;
// parameters
if(!t.empty()) {
size_t ridx = query.find_first_of('?');
if(ridx != string::npos && ridx + 1 < t.size()) {
query_without_parameters = query.substr(0, ridx);
t = query.substr(ridx + 1);
vector<string> parts = str::split(t, "&");
for(string& part : parts) {
size_t eqidx = part.find_first_of('=');
string key = part;
string value;
if(eqidx != string::npos && eqidx < part.size()) {
value = key.substr(eqidx + 1);
key = key.substr(0, eqidx);
}
parameters.emplace_back(key, value);
}
}
}
}
std::string url::to_string() {
string r = format("{}://{}{}", protocol, host, query_without_parameters);
if(!parameters.empty()) {
r += "?";
for(int i = 0; i < parameters.size(); i++) {
if(i > 0) r += "&";
r += parameters[i].first;
if(!parameters[i].second.empty()) {
r += "=";
r += parameters[i].second;
}
}
}
return r;
}