fix: 修复utf8的校验和json返回类型

This commit is contained in:
hugy 2023-04-25 08:48:16 +08:00
parent 6105789fcc
commit f9a7924658
4 changed files with 39 additions and 15 deletions

View File

@ -123,9 +123,9 @@ int DB::Select(DWORD db_hanle, const char *sql,
string content(it[i].content); string content(it[i].content);
item.push_back(content); item.push_back(content);
} else { } else {
string b64_str = string base64_str =
base64_encode((BYTE *)it[i].content, it[i].content_len); base64_encode((BYTE *)it[i].content, it[i].content_len);
item.push_back(b64_str); item.push_back(base64_str);
} }
} else { } else {

View File

@ -588,7 +588,7 @@ void HttpHandler::HandlerRequest(struct mg_connection *c, void *ev_data) {
ret = res.dump(); ret = res.dump();
} }
if (ret != "") { if (ret != "") {
mg_http_reply(c, 200, "", ret.c_str(), 0, 0); mg_http_reply(c, 200, "Content-Type: application/json\r\n", "%s\n", ret.c_str());
} }
} else { } else {
mg_http_reply(c, 500, NULL, "%s", "Invalid URI"); mg_http_reply(c, 500, NULL, "%s", "Invalid URI");

View File

@ -172,19 +172,43 @@ std::string Utils::WCharToUTF8(wchar_t *wstr) {
return std::string(); return std::string();
} }
bool Utils::IsTextUtf8(const char *str, int len) { bool Utils::IsTextUtf8(const char *str,int length) {
int needed = MultiByteToWideChar(CP_UTF8, 0, str, len, NULL, 0); char endian = 1;
wchar_t *wide_str = new wchar_t[needed]; bool littlen_endian = (*(char *)&endian == 1);
MultiByteToWideChar(CP_UTF8, 0, str, len, wide_str, needed);
char *new_str = new char[len + 1]; size_t i;
WideCharToMultiByte(CP_ACP, 0, wide_str, -1, new_str, len + 1, NULL, NULL); int bytes_num;
unsigned char chr;
bool isUtf8 = strcmp(str, new_str) == 0; i = 0;
bytes_num = 0;
while (i < length) {
if (littlen_endian) {
chr = *(str + i);
} else { // Big Endian
chr = (*(str + i) << 8) | *(str + i + 1);
i++;
}
delete[] wide_str; if (bytes_num == 0) {
delete[] new_str; if ((chr & 0x80) != 0) {
while ((chr & 0x80) != 0) {
return isUtf8; chr <<= 1;
bytes_num++;
}
if ((bytes_num < 2) || (bytes_num > 6)) {
return false;
}
bytes_num--;
}
} else {
if ((chr & 0xC0) != 0x80) {
return false;
}
bytes_num--;
}
i++;
}
return (bytes_num == 0);
} }
} // namespace wxhelper } // namespace wxhelper

View File

@ -47,7 +47,7 @@ class Utils {
static std::string WCharToUTF8(wchar_t *wstr); static std::string WCharToUTF8(wchar_t *wstr);
static bool IsTextUtf8(const char *str, int len); static bool IsTextUtf8(const char * str,int length) ;
template <typename T1, typename T2> template <typename T1, typename T2>
static std::vector<T1> split(T1 str, T2 letter) { static std::vector<T1> split(T1 str, T2 letter) {