Add htmlTranslate() method

This commit is contained in:
antao 2019-02-27 10:36:03 +08:00
parent 082f895e29
commit 49c03ee707
3 changed files with 55 additions and 0 deletions

View File

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

View File

@ -119,6 +119,15 @@ class HttpViewData
return _viewData[key];
}
/// Translate some special characters to HTML format, such as:
/**
* " --> &quot;
* & --> &amp;
* < --> &lt;
* > --> &gt;
*/
static std::string htmlTranslate(const std::string &str);
protected:
typedef std::unordered_map<std::string, any> ViewDataMap;
mutable ViewDataMap _viewData;

45
lib/src/HttpViewData.cc Normal file
View File

@ -0,0 +1,45 @@
/**
*
* HttpViewData.cc
* An Tao
*
* Copyright 2018, An Tao. All rights reserved.
* https://github.com/an-tao/drogon
* Use of this source code is governed by a MIT license
* that can be found in the License file.
*
* Drogon
*
*/
#include <drogon/HttpViewData.h>
using namespace drogon;
std::string HttpViewData::htmlTranslate(const std::string &str)
{
std::string ret;
ret.reserve(str.length());
for (auto &ch : str)
{
switch (ch)
{
case '"':
ret.append("&quot;");
break;
case '<':
ret.append("&lt;");
break;
case '>':
ret.append("&gt;");
break;
case '&':
ret.append("&amp;");
break;
default:
ret.push_back(ch);
break;
}
}
return ret;
}