Nginx:如何将帖子数据编码从UTF-8转换为TIS-620,然后再通过代理传递

问题描述 投票:0回答:2

我想转换从请求收到的POST数据并将其从UTF-8转换为TIS-620,然后使用下面的代码通过proxy_pass传递给后端,但我不知道这样做的方法

location / {
   proxy_pass http://targetwebsite;
}

如果我没有错,我相信我必须使用Lua module来操纵请求,但我不知道它们是否支持任何字符转换。

有没有人可以帮助我使用LUA将示例代码转换为UTF-8 toTIS-620的POST数据,以及如何在转换之前验证POST数据是否为UTF-8,或者是否有更好的方法来操作/转换nginx中的POST数据?

nginx lua
2个回答
1
投票

该解决方案适用于Lua 5.1 / 5.2 / 5.3

local function utf8_to_unicode(utf8str, pos)
   -- pos = starting byte position inside input string
   local code, size = utf8str:byte(pos), 1
   if code >= 0xC0 and code < 0xFE then
      local mask = 64
      code = code - 128
      repeat
         local next_byte = utf8str:byte(pos + size)
         if next_byte and next_byte >= 0x80 and next_byte < 0xC0 then
            code, size = (code - mask - 2) * 64 + next_byte, size + 1
         else
            return
         end
         mask = mask * 32
      until code < mask
   elseif code >= 0x80 then
      return
   end
   -- returns code, number of bytes in this utf8 char
   return code, size
end

function utf8to620(utf8str)
   local pos, result_620 = 1, {}
   while pos <= #utf8str do
      local code, size = utf8_to_unicode(utf8str, pos)
      if code then
         pos = pos + size
         code =
            (code < 128 or code == 0xA0) and code
            or (code >= 0x0E01 and code <= 0x0E3A or code >= 0x0E3F and code <= 0x0E5B) and code - 0x0E5B + 0xFB
      end
      if not code then
         return utf8str  -- wrong UTF-8 symbol, this is not a UTF-8 string, return original string
      end
      table.insert(result_620, string.char(code))
   end
   return table.concat(result_620)  -- return converted string
end

用法:

local utf8string = "UTF-8 Thai text here"
local tis620string = utf8to620(utf8string)

0
投票

我在Wikipedia上查找了编码,并提出了以下解决方案,用于从UTF-8转换为TIS-620。它假定UTF-8字符串中的所有代码点都具有TIS-620中的编码。如果UTF-8字符串仅包含ASCII可打印字符(代码点" ""~")或泰语字符(代码点"ก""๛"),它将起作用。否则,它将给出错误的,可能非常奇怪的结果。

这假设你有Lua 5.3的utf8库或同等的库。如果您使用的是早期版本的Lua,则可能是MediaWiki的pure-Lua version库的ustring(例如维基百科和维基词典)。它提供了验证UTF-8的功能,许多其他功能将自动验证字符串。 (也就是说,如果字符串是无效的UTF-8,它们会抛出一个错误。)如果你使用那个库,你只需要在下面的代码中用utf8.codepoint替换ustring.codepoint

-- Add this number to TIS-620 values above 0x80 to get the Unicode codepoint.
-- 0xE00 is the first codepoint of Thai block, 0xA0 is the corresponding byte used in TIS-620.
local difference = 0xE00 - 0xA0

function UTF8_to_TIS620(UTF8_string)
    local TIS620_string = UTF8_string:gsub(
      '[\194-\244][\128-\191]+',
      function (non_ASCII)
          return string.char(utf8.codepoint(non_ASCII) - difference)
      end)
    return TIS620_string
end
© www.soinside.com 2019 - 2024. All rights reserved.