luaapi-gatewaykrakend

krakend lua scripting fail by load lib


 "endpoint": "/apps/{id}",
      "output_encoding": "no-op",
      "method": "GET",
      "backend": [
        {
          "host": [
            "http://xxx.yyy.zz:8888"
          ],
          "url_pattern": "/apps/{id}",
          "extra_config": {
            "modifier/lua-backend": {
              "sources": [
                "/etc/krakend/Hello.lua"
              ],
              "post": "local r = response.load(); printPostBody(r:body());",
              "allow_open_libs": true
            }
          }
        }
      ]
    }, 

My Hello.lua:

local mylua = require("cjson")

function printPostBody(body)
    print(body);
end

When i add this part: local mylua = require("cjson") i got this error:

2023/10/08 09:36:23 [Recovery] 2023/10/08 - 09:36:23 panic recovered:
runtime error: slice bounds out of range [-1:]
/usr/local/go/src/runtime/panic.go:153 (0xf3dc7e)
/go/pkg/mod/github.com/krakendio/binder@v0.0.0-20230413105421-1bbe94e65f45/error.go:140 (0x1971f64)
/go/pkg/mod/github.com/krakendio/binder@v0.0.0-20230413105421-1bbe94e65f45/binder.go:27 (0x1970866)
/go/pkg/mod/github.com/krakendio/binder@v0.0.0-20230413105421-1bbe94e65f45/error.go:201 (0x1972397)
/go/pkg/mod/github.com/krakendio/binder@v0.0.0-20230413105421-1bbe94e65f45/binder.go:43 (0x19707ee)
/go/pkg/mod/github.com/krakendio/binder@v0.0.0-20230413105421-1bbe94e65f45/binder.go:26 (0x1970785)
/go/pkg/mod/github.com/krakendio/krakend-lua/v2@v2.1.2/proxy/proxy.go:75 (0x1979793)
/go/pkg/mod/github.com/luraproject/lura/v2@v2.3.0/proxy/balancing.go:77 (0x13080a8)
/go/pkg/mod/github.com/luraproject/lura/v2@v2.3.0/proxy/http.go:113 (0x130db84)
/go/pkg/mod/github.com/luraproject/lura/v2@v2.3.0/router/gin/endpoint.go:50 (0x1bbf674)
/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 (0x1bb49c1)
/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/recovery.go:102 (0x1bb49ac)
/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 (0x1bb3ae6)
/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/logger.go:240 (0x1bb3ac9)
/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/context.go:174 (0x1bb296a)
/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/gin.go:620 (0x1bb25f1)
/go/pkg/mod/github.com/gin-gonic/gin@v1.9.1/gin.go:576 (0x1bb211c)
/usr/local/go/src/net/http/server.go:2936 (0x128a0b5)
/usr/local/go/src/net/http/server.go:1995 (0x1285251)
/usr/local/go/src/runtime/asm_amd64.s:1598 (0xf761a0)

Solution

  • As you have seen, if you remove the line with a require that will work. The thing with Lua in KrakenD is that is not a regular Lua engine, but kind of a virtual machine that is restricted to the standard library and has no dependency injection. You cannot use Lua Rocks neither import anything that is not under the sources directory.

    So you cannot import Lua libraries like this (require). If you want to include JSON parsing libraries you will need to import them by hand under sources.