Optimize the htmlTranslate method

This commit is contained in:
antao 2019-07-08 13:49:01 +08:00
parent 5c5f0bf812
commit 47c6bc20f4
3 changed files with 51 additions and 11 deletions
examples/simple_example
lib

View File

@ -44,9 +44,9 @@ void ApiTest::your_method_name(
std::map<std::string, std::string> para; std::map<std::string, std::string> para;
para["p1"] = std::to_string(p1); para["p1"] = std::to_string(p1);
para["p2"] = std::to_string(p2); para["p2"] = std::to_string(p2);
para["p3"] = HttpViewData::htmlTranslate( para["p3"] = HttpViewData::htmlTranslate(string_view(
"<script>alert(\" This should not be displayed in a browser alert " "<script>alert(\" This should not be displayed in a browser alert "
"box.\");</script>"); "box.\");</script>"));
data.insert("parameters", para); data.insert("parameters", para);
auto res = HttpResponse::newHttpViewResponse("ListParaView", data); auto res = HttpResponse::newHttpViewResponse("ListParaView", data);
callback(res); callback(res);

View File

@ -136,6 +136,41 @@ class HttpViewData
* > --> &gt; * > --> &gt;
*/ */
static std::string htmlTranslate(const std::string &str); static std::string htmlTranslate(const std::string &str);
static std::string htmlTranslate(const string_view &str);
static bool needTranslation(const std::string &str)
{
for (auto const &c : str)
{
switch (c)
{
case '"':
case '&':
case '<':
case '>':
return true;
default:
continue;
}
}
return false;
}
static bool needTranslation(const string_view &str)
{
for (auto const &c : str)
{
switch (c)
{
case '"':
case '&':
case '<':
case '>':
return true;
default:
continue;
}
}
return false;
}
protected: protected:
typedef std::unordered_map<std::string, any> ViewDataMap; typedef std::unordered_map<std::string, any> ViewDataMap;

View File

@ -17,24 +17,29 @@
using namespace drogon; using namespace drogon;
std::string HttpViewData::htmlTranslate(const std::string &str) std::string HttpViewData::htmlTranslate(const std::string &str)
{
return htmlTranslate(string_view(str));
}
std::string HttpViewData::htmlTranslate(const string_view &str)
{ {
std::string ret; std::string ret;
ret.reserve(str.length()); ret.reserve(str.length() + 64);
for (auto &ch : str) for (auto &ch : str)
{ {
switch (ch) switch (ch)
{ {
case '"': case '"':
ret.append("&quot;"); ret.append("&quot;", 6);
break;
case '<':
ret.append("&lt;");
break;
case '>':
ret.append("&gt;");
break; break;
case '&': case '&':
ret.append("&amp;"); ret.append("&amp;", 5);
break;
case '<':
ret.append("&lt;", 4);
break;
case '>':
ret.append("&gt;", 4);
break; break;
default: default:
ret.push_back(ch); ret.push_back(ch);