lua-resty-ffi provides a general and efficient interface, allowing you to use Go, Python, Java and Rust to directly develop the functions you want for OpenResty/Nginx.
As we all know, the lua and C used by OpenResty have a weak ecology, and many rebuilt wheels lack maintenance, so that it is difficult for a smart woman to cook without rice when interoperating with the peripheral ecosystem.
feature:
- Non-blocking, run as a coroutine
- Simple and extensible interface that supports any language that conforms to the C ABI
- Once and for all, no need to write any C or Lua modules to develop new functions
- High performance, faster than unix domain socket
- Universal java, python loader
- Use any message serialization format you like
The simplest example:
Use golang to develop an echo function.
Create a file: echo.go
package main
/*
#cgo LDFLAGS: -shared
#include <string.h>
void* ngx_http_lua_ffi_task_poll(void *p);
char* ngx_http_lua_ffi_get_req(void *tsk, int *len);
void ngx_http_lua_ffi_respond(void *tsk, int rc, char* rsp, int rsp_len);
*/
import "C"
import (
"log"
"unsafe"
)
//export libffi_init
func libffi_init(cfg_cstr *C.char, tq unsafe.Pointer) C.int {
log.Println("start go echo runtime")
go func() {
for {
task := C.ngx_http_lua_ffi_task_poll(tq)
if task == nil {
break
}
var rlen C.int
r := C.ngx_http_lua_ffi_get_req(task, &rlen)
res := C.malloc(C.ulong(rlen))
C.memcpy(res, unsafe.Pointer(r), C.ulong(rlen))
C.ngx_http_lua_ffi_respond(task, 0, (*C.char)(res), rlen)
}
log.Println("exit go echo runtime")
}()
return 0
}
func main() {}
Create a file: nginx.conf
daemon off;
error_log /dev/stderr info;
worker_processes auto;
env LD_LIBRARY_PATH;
events {}
http {
server {
listen 20000;
location /echo {
content_by_lua_block {
local demo = ngx.load_ffi("ffi_go_echo")
local ok, res = demo:echo("foobar")
assert(ok)
assert(res == "foobar")
demo:__unload()
ok, res = demo:echo("foobar")
assert(not ok)
ngx.log(ngx.ERR, res)
ngx.say("ok")
}
}
}
}
run:
go build -buildmode=c-shared -o libffi_go_echo.so echo.go
LD_LIBRARY_PATH=$(PWD) $(NGINX_BIN) -p $(PWD) -c nginx.conf
curl localhost:20000/echo
#luarestyffi #Homepage #Documentation #Download #OpenRestyNginx #Common #Interface #News Fast Delivery