Krakend how to set a modified response body with lua script

452 views
Skip to first unread message

Emo Leumassi

unread,
Oct 23, 2023, 9:22:00 AM10/23/23
to KrakenD Community

I wrote a lua script to transform a response body in jsonapi in json without arrays or collections. But i can't set the response body of the modified body. The request returns a Error aborted

My configuration file:

{ "$schema": "https://www.krakend.io/schema/v3.json", "version": 3, "port": 9000, "timeout": "300000s", "cache_ttl": "4000s", "client_tls": { "allow_insecure_connections": true }, "extra_config": { "router": { "return_error_msg": true } }, "endpoints": [ { "@comment": "Feature: GET by id", "endpoint": "/path/to-service/{id}", "output_encoding": "no-op", "method": "GET", "backend": [ { "host": [ "https://xxx.yyy.zzz." ], "url_pattern": "/path/to-service/{id}", "extra_config": { "modifier/lua-backend": { "sources": [ "/etc/krakend/flatten.lua", "/etc/krakend/json_rxi.lua", "/etc/krakend/json_modifier.lua" ], "post": "local r = response.load(); modifyBody(r);", "live": true, "allow_open_libs": true } } } ] } ] }

my json_modifiert.lua:

local json = require "json_rxi"

local flatten = require "flatten"

function modifyBody(response) local parsedJson = json.decode(response:body()) local result = {} local jsonItems = {} for k, v in pairs(flatten(parsedJson, ".", nil, result)) do table.insert(jsonItems, "\"" .. k .. "\":\"" .. tostring(v) .. "\"") end local newResponse = "{" .. table.concat(jsonItems, ",") .. "}" response:body(newResponse) print(type(response:body())) ---> String print(type(response:body())) ---> printed response:body(newResponse) end

Commands [used:]

version: "3"

services: krakend_ce: image: devopsfaith/krakend:watch volumes: - ./krakend:/etc/krakend ports: - "9000:9000" command: ["run", "-d", "-c", "/etc/krakend/krakend.json"] docker-compose -f docker-compose.yml up -d

Logs:

[00] {"data":{"id":"xxxxx","type":"yyyy",.......}} [00] string [00] [GIN] 2023/10/23 - 10:17:30 | 200 | 722.459633ms | 172.20.0.1 | GET "/path/to-service/identification"

Additional comments:

When i called http://localhost:9000/path/to-service/identification, i got

Could not get response

Error: aborted

but the modified body is printed und json conform.

Albert Lombarte

unread,
Oct 25, 2023, 11:58:34 AM10/25/23
to KrakenD Community, KrakenD Community
This is because you cannot do this:

local json = require "json_rxi"

local flatten = require "flatten"


Add files under "sources" instead


El dia dilluns, 23 d’octubre de 2023 a les 15:22:00 UTC+2, KrakenD Community va escriure:

Emo Leumassi

unread,
Oct 26, 2023, 1:39:36 AM10/26/23
to KrakenD Community, Albert Lombarte, KrakenD Community
It wasn't the problem. I already have added the files under sources. 

change the `Content-Length` resolved the problem.

```
response:body(newBody)
response:headers("Content-Length", tostring(string.len(newBody)))
```

Reply all
Reply to author
Forward
0 new messages