Skip to content

Commit 78ea786

Browse files
authored
[PR] Special function to encode query params (yhirose#801)
* Special function to encode query params * Fix #include <iomanip> * Added unescaped charsets to encode_query_param * Unit tests for encode_query_param
1 parent 9cac2c9 commit 78ea786

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

httplib.h

Lines changed: 29 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,7 @@ using socket_t = int;
203203
#include <string>
204204
#include <sys/stat.h>
205205
#include <thread>
206+
#include <iomanip>
206207

207208
#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
208209
#include <openssl/err.h>
@@ -214,7 +215,6 @@ using socket_t = int;
214215
#include <openssl/applink.c>
215216
#endif
216217

217-
#include <iomanip>
218218
#include <iostream>
219219
#include <sstream>
220220

@@ -1457,6 +1457,33 @@ inline bool is_valid_path(const std::string &path) {
14571457
return true;
14581458
}
14591459

1460+
inline std::string encode_query_param(const std::string &value){
1461+
std::ostringstream escaped;
1462+
escaped.fill('0');
1463+
escaped << std::hex;
1464+
1465+
for (char const &c: value) {
1466+
if (std::isalnum(c) ||
1467+
c == '-' ||
1468+
c == '_' ||
1469+
c == '.' ||
1470+
c == '!' ||
1471+
c == '~' ||
1472+
c == '*' ||
1473+
c == '\'' ||
1474+
c == '(' ||
1475+
c == ')') {
1476+
escaped << c;
1477+
} else {
1478+
escaped << std::uppercase;
1479+
escaped << '%' << std::setw(2) << static_cast<int>(static_cast<unsigned char>(c));
1480+
escaped << std::nouppercase;
1481+
}
1482+
}
1483+
1484+
return escaped.str();
1485+
}
1486+
14601487
inline std::string encode_url(const std::string &s) {
14611488
std::string result;
14621489

@@ -3045,7 +3072,7 @@ inline std::string params_to_query_str(const Params &params) {
30453072
if (it != params.begin()) { query += "&"; }
30463073
query += it->first;
30473074
query += "=";
3048-
query += encode_url(it->second);
3075+
query += encode_query_param(it->second);
30493076
}
30503077
return query;
30513078
}

test/test.cc

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,18 @@ TEST(StartupTest, WSAStartup) {
4646
}
4747
#endif
4848

49+
TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest){
50+
string unescapedCharacters = "-_.!~*'()";
51+
52+
EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
53+
}
54+
55+
TEST(EncodeQueryParamTest, ParseReservedCharactersTest){
56+
string reservedCharacters = ";,/?:@&=+$";
57+
58+
EXPECT_EQ(detail::encode_query_param(reservedCharacters), "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
59+
}
60+
4961
TEST(TrimTests, TrimStringTests) {
5062
EXPECT_EQ("abc", detail::trim_copy("abc"));
5163
EXPECT_EQ("abc", detail::trim_copy(" abc "));

0 commit comments

Comments
 (0)