Skip to content

Commit

Permalink
[PR] Special function to encode query params (yhirose#801)
Browse files Browse the repository at this point in the history
* Special function to encode query params

* Fix #include <iomanip>

* Added unescaped charsets to encode_query_param

* Unit tests for encode_query_param
  • Loading branch information
Yrds authored Dec 18, 2020
1 parent 9cac2c9 commit 78ea786
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 2 deletions.
31 changes: 29 additions & 2 deletions httplib.h
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ using socket_t = int;
#include <string>
#include <sys/stat.h>
#include <thread>
#include <iomanip>

#ifdef CPPHTTPLIB_OPENSSL_SUPPORT
#include <openssl/err.h>
Expand All @@ -214,7 +215,6 @@ using socket_t = int;
#include <openssl/applink.c>
#endif

#include <iomanip>
#include <iostream>
#include <sstream>

Expand Down Expand Up @@ -1457,6 +1457,33 @@ inline bool is_valid_path(const std::string &path) {
return true;
}

inline std::string encode_query_param(const std::string &value){
std::ostringstream escaped;
escaped.fill('0');
escaped << std::hex;

for (char const &c: value) {
if (std::isalnum(c) ||
c == '-' ||
c == '_' ||
c == '.' ||
c == '!' ||
c == '~' ||
c == '*' ||
c == '\'' ||
c == '(' ||
c == ')') {
escaped << c;
} else {
escaped << std::uppercase;
escaped << '%' << std::setw(2) << static_cast<int>(static_cast<unsigned char>(c));
escaped << std::nouppercase;
}
}

return escaped.str();
}

inline std::string encode_url(const std::string &s) {
std::string result;

Expand Down Expand Up @@ -3045,7 +3072,7 @@ inline std::string params_to_query_str(const Params &params) {
if (it != params.begin()) { query += "&"; }
query += it->first;
query += "=";
query += encode_url(it->second);
query += encode_query_param(it->second);
}
return query;
}
Expand Down
12 changes: 12 additions & 0 deletions test/test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ TEST(StartupTest, WSAStartup) {
}
#endif

TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest){
string unescapedCharacters = "-_.!~*'()";

EXPECT_EQ(detail::encode_query_param(unescapedCharacters), "-_.!~*'()");
}

TEST(EncodeQueryParamTest, ParseReservedCharactersTest){
string reservedCharacters = ";,/?:@&=+$";

EXPECT_EQ(detail::encode_query_param(reservedCharacters), "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
}

TEST(TrimTests, TrimStringTests) {
EXPECT_EQ("abc", detail::trim_copy("abc"));
EXPECT_EQ("abc", detail::trim_copy(" abc "));
Expand Down

0 comments on commit 78ea786

Please sign in to comment.