lua-nginx-module icon indicating copy to clipboard operation
lua-nginx-module copied to clipboard

New API for sending ffi buffer in tcpsock without casting to string

Open dqminh opened this issue 6 years ago • 1 comments
trafficstars

This expose a way to set the tcp upstream socket's request buffer manually, so we can call write later. The reason this is splitted into 2 functions is because i couldn't find a way to send cdata over in a cfunction sanely.

Here is roughly how you can use them

local ffi = require "ffi"
local base = require "resty.core.base"

local C = ffi.C
local error = error
local errmsg = base.get_errmsg_ptr()
local FFI_OK = base.FFI_OK

ffi.cdef[[
int ngx_http_lua_socket_tcp_ffi_set_buf(ngx_http_request_t *r, void *u, void *cdata_ctx, size_t len, char **err);
]]

local function check_tcp(tcp)
  if not tcp or type(tcp) ~= "table" then
    return error("bad \"tcp\" argument")
  end
  tcp = tcp[1]
  if type(tcp) ~= "userdata" then
    return error("bad \"tcp\" argument")
  end
  return tcp
end

local function ffi_set_buffer(tcp, buffer, len)
  tcp = check_tcp(tcp)
  local r = base.get_request()
  if not r then
    return error("no request found")
  end
  local rc = C.ngx_http_lua_socket_tcp_ffi_set_buf(r, tcp, buffer, len, errmsg)
  if rc ~= FFI_OK then
    return nil, ffi.string(errmsg[0])
  end
  return true
end

local sock = ngx.socket.tcp()
sock:connect("unix:/tmp/go.sock")
sock:settimeout(1000)
ffi_set_buffer(sock, data, len)
sock:ffi_send()

I hereby granted the copyright of the changes in this pull request to the authors of this lua-nginx-module project.

dqminh avatar Mar 04 '19 16:03 dqminh

This pull request is now in conflict :(

mergify[bot] avatar Jul 20 '20 04:07 mergify[bot]