Krakend lua set response body returns nil

119 views Asked by At

i wrote a lua script to modify the response of my request. How it is possible to return de response of the lua script. I got the initial response of the request and not the modified response.

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

My Hello.lua

function  modifyBody(response)
print(response:body()) //return the body
local json_parse = json_parse(response);
print(json_parse) //return the modified body
print(response:body(json_parse)) //return the modified body
print(response) //return userdata: 0xc000618b10
return response:body(json_parse)
end

i got a 200 from the container:

[00] 2023/10/18 09:18:21 KRAKEND INFO: [SERVICE: Gin] Listening on port: 9000
[00] [GIN] 2023/10/18 - 09:18:27 | 200 |  312.644487ms |      172.20.0.1 | GET      "/apps/aaaaa"

print(json_parse) the logs returns a correct formated json but the but the postman console is empty:

Could not get response
Error: aborted

i tried another combination:

"output_encoding": "json", //endpoint level
"encoding": "no-op", //backend level -> empty json {}
"output_encoding": "json", //endpoint level
"encoding": "json", //backend level ->

2023/10/19 15:06:33 KRAKEND ERROR: [ENDPOINT: /apps/:id] unexpected character '' at line 1 col 1
[00] [GIN] 2023/10/19 - 15:06:33 | 500 |  578.746497ms |      172.20.0.1 | GET      "/ apps  /11111"

enter image description here

1

There are 1 answers

0
emoleumassi On

change the Content-Length resolved the problem.

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