Browse Source

Add hv::escapeURL, hv::escapeHTML

ithewei 2 years ago
parent
commit
0595007aeb
3 changed files with 33 additions and 4 deletions
  1. 22 0
      cpputil/hurl.cpp
  2. 10 3
      cpputil/hurl.h
  3. 1 1
      examples/curl.cpp

+ 22 - 0
cpputil/hurl.cpp

@@ -182,3 +182,25 @@ const std::string& HUrl::dump() {
     }
     return url;
 }
+
+namespace hv {
+
+std::string escapeHTML(const std::string& str)  {
+    std::string ostr;
+    const char* p = str.c_str();
+    while (*p != '\0') {
+        switch (*p) {
+            case '<':   ostr += "&lt;";     break;
+            case '>':   ostr += "&gt;";     break;
+            case '&':   ostr += "&amp;";    break;
+            case '\"':  ostr += "&quot;";   break;
+            case '\'':  ostr += "&apos;";   break;
+         // case ' ':   ostr += "&nbsp;";   break;
+            default:    ostr += *p;         break;
+        }
+        ++p;
+    }
+    return ostr;
+}
+
+}

+ 10 - 3
cpputil/hurl.h

@@ -9,9 +9,6 @@ class HV_EXPORT HUrl {
 public:
     static std::string escape(const std::string& str, const char* unescaped_chars = "");
     static std::string unescape(const std::string& str);
-    static inline std::string escapeUrl(const std::string& url) {
-        return escape(url, ":/@?=&#+");
-    }
 
     HUrl() : port(0) {}
     ~HUrl() {}
@@ -31,4 +28,14 @@ public:
     std::string fragment;
 };
 
+namespace hv {
+
+HV_INLINE std::string escapeURL(const std::string& url) {
+    return HUrl::escape(url, ":/@?=&#+");
+}
+
+HV_EXPORT std::string escapeHTML(const std::string& str);
+
+} // end namespace hv
+
 #endif // HV_URL_H_

+ 1 - 1
examples/curl.cpp

@@ -263,7 +263,7 @@ int main(int argc, char* argv[]) {
             req.method = HTTP_POST;
         }
     }
-    req.url = HUrl::escapeUrl(url);
+    req.url = hv::escapeURL(url);
     req.http_cb = [](HttpMessage* res, http_parser_state state, const char* data, size_t size) {
         if (state == HP_HEADERS_COMPLETE) {
             if (verbose) {