The 500 error occurs because HAProxy's Lua API encounters an error when processing the response value in your code. Here's a breakdown of the issue and how to resolve it:
Root Cause
The reply:set_body(response) method expects a string parameter. If response is not a valid string (e.g., nil, a table, a number, or malformed data), HAProxy will throw an error internally, resulting in a 500 status code.
Common Scenarios
response is nil
If response is undefined or accidentally nil, set_body(nil) will fail.
response is not a string
If response is a number, boolean, table, or other non-string type, Lua will not implicitly convert it to a string in this context.
Invalid XML/Content
If response contains invalid characters or malformed XML, HAProxy might reject it (though this typically affects the client, not the server response).
Debugging Steps
Check the Type of response
Add debug logs to verify the type and value of response:
If type(response) is not "string", you need to convert it.
Check HAProxy Logs
Look for Lua-related errors in HAProxy's logs (e.g., /var/log/haproxy.log). Errors like attempt to concatenate a nil value indicate issues with response.
Solutions
Ensure response is a String
Explicitly convert response to a string before setting the body:
lua
reply:set_body(tostring(response))
Validate response Before Setting
Add checks to handle edge cases:
lua
if type(response) ~= "string" then
response = "[ERROR: Invalid response]"
end
reply:set_body(response)
Handle nil or Empty Values
If response might be nil, provide a default:
lua
response = response or "" -- Default to empty string if nil
reply:set_body(response)
Sanitize XML Content
If response is XML, ensure it’s properly escaped/validated to avoid parsing issues.
Example Fix
lua
local reply = txn:reply()
reply:set_status(200)
reply:add_header("Content-Type", "application/xml")
reply:add_header("cache-control", "no-cache")
reply:add_header("cache-control", "no-store")
-- Ensure response is a valid string
if type(response) ~= "string" then
response = tostring(response) or "" -- Fallback to empty string
end
reply:set_body(response)
txn:done(reply)
Key Takeaway
The 500 error stems from HAProxy’s Lua API failing to process response as a valid string. Explicitly converting response to a string and validating its content will resolve the issue. Check HAProxy’s logs for specific error messages to pinpoint the exact cause.