0% found this document useful (0 votes)
25 views

LUA Script Parsing Tutorial

Uploaded by

abdlwhapahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

LUA Script Parsing Tutorial

Uploaded by

abdlwhapahmed
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

LUA script parsing tutorial

core.Alert ("LUA script parseElementWhatsAppCloud loaded");

function get_value_of_key(payload, key)


strlen = string.len(payload)

startKeyIndex, endKeyIndex = string.find(payload,key)


if(startKeyIndex == nil)
then
return "Cannot Find your key: " .. key
end
--print(startKeyIndex, endKeyIndex)
--print(string.sub(payload,startKeyIndex, endKeyIndex) )

startFQIndex, endFQIndex = string.find(payload,"\"", endKeyIndex+2)


if(startFQIndex == nil)
then
return "Cannot Find starting quotation"
end

--print(startFQIndex, endFQIndex)
--print(string.sub(payload,startFQIndex, endFQIndex) )

startSQIndex, endSQIndex = string.find(payload,"\"", endFQIndex+1)


if(startSQIndex == nil)
then
return "Cannot Find closing quotation"
end

--print(startSQIndex, endSQIndex)
--print(string.sub(payload,startSQIndex, endSQIndex) )

value = string.sub(payload,endFQIndex + 1, startSQIndex-1)

--print(value)

if(value == nil)
then
return "return of get_value_of_key is NONE"
end

return value
end

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/5
function parseElementWhatsAppCloud(txn, salt)
local payload = txn.sf:req_body()
core.log(core.debug, "CloudAPIPayLoad: " .. payload)

if(payload == nil)
then
return "ERROR_GETTING_payload"
end

return get_value_of_key(payload, "from")


end

-- register HAProxy "fetch"


core.register_fetches ("parseElementWhatsAppCloud", parseElementWhatsAppCloud)

Your Lua script defines a function `parseElementWhatsAppCloud` that extracts the value of a specific key
("from") from the payload of an HTTP request body in HAProxy. This function uses `get_value_of_key` to
search the payload and retrieve the value associated with the key. Here’s a quick overview of how this
script works and potential improvements:

Key Functions and Logic:

1. `get_value_of_key(payload, key)`:
Searches for the position of a specified key in a payload.
After locating the key, it searches for starting and closing quotation marks around the value.
If any part of the key or quotation marks is missing, it returns an error message.
If successful, it extracts and returns the value associated with the key.
2. `parseElementWhatsAppCloud(txn, salt)`:
Retrieves the HTTP request body with `txn.sf:req_body()`.
Logs the payload and then calls `get_value_of_key` to extract the "from" key’s value from the
payload.
Returns the extracted value or error messages as needed.
3. Registration:
Registers `parseElementWhatsAppCloud` as a fetch function, allowing it to be called within
HAProxy.

Suggestions for Improvement:

1. Error Handling: The error messages in `get_value_of_key` can be made more descriptive to help
debug specific issues in payload parsing.

2. String Search Optimization: To improve readability, consider modularizing repeated string-search


logic into helper functions.

3. Logging: Additional debug logs can help trace exact matches and values returned in case of errors.
Consider adding more detailed logs for key steps in the parsing process.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/5
This script looks solid for extracting values from a JSON-like payload in HAProxy. If the payload format
varies, handling those cases may require additional logic. Let me know if you'd like help with any further
customization!

need to add comments to all lines

Adding comments to each line of your Lua script will provide more clarity on its functionality and the
purpose of each section. Here’s your code with comments explaining each line:

lua

-- Core alert message indicating that the Lua script for parseElementWhatsAppCloud is loaded
core.Alert("LUA script parseElementWhatsAppCloud loaded")

-- Function to retrieve the value associated with a specific key from a given payload
function get_value_of_key(payload, key)
-- Get the length of the payload string
strlen = string.len(payload)

-- Find the start and end indices of the key in the payload
startKeyIndex, endKeyIndex = string.find(payload, key)
if (startKeyIndex == nil) then
-- If the key is not found, return an error message
return "Cannot Find your key: " .. key
end

-- Locate the starting quotation mark for the key's value after the key
startFQIndex, endFQIndex = string.find(payload, "\"", endKeyIndex + 2)
if (startFQIndex == nil) then
-- If starting quotation is not found, return an error message
return "Cannot Find starting quotation"
end

-- Locate the closing quotation mark for the key's value after the starting quotation
startSQIndex, endSQIndex = string.find(payload, "\"", endFQIndex + 1)
if (startSQIndex == nil) then
-- If closing quotation is not found, return an error message
return "Cannot Find closing quotation"
end

-- Extract the value between the quotations by taking a substring from payload
value = string.sub(payload, endFQIndex + 1, startSQIndex - 1)

-- Check if value extraction returned nil; if so, return an error message


if (value == nil) then
return "return of get_value_of_key is NONE"
end

-- Return the extracted value


return value
end

-- Function to parse the 'from' element in a WhatsApp Cloud API payload using a transaction
object
function parseElementWhatsAppCloud(txn, salt)
-- Retrieve the request body from the transaction object
local payload = txn.sf:req_body()

-- Log the payload for debugging purposes


core.log(core.debug, "CloudAPIPayLoad: " .. payload)

-- Check if payload retrieval was successful

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/5
if (payload == nil) then
-- Return an error message if payload is nil
return "ERROR_GETTING_payload"
end

-- Call the helper function to get the value for the key "from" in the payload
return get_value_of_key(payload, "from")
end

-- Register the parseElementWhatsAppCloud function as a fetch function in HAProxy


core.register_fetches("parseElementWhatsAppCloud", parseElementWhatsAppCloud)

This version includes comments for each line to explain the purpose of each part of the script. This
should improve readability and help future developers understand its workings quickly. Let me know if
there are specific areas where you'd like even more detail!

why i use this script

This Lua script is designed to be used in HAProxy as a way to extract specific data from an HTTP
request's body, specifically for requests related to WhatsApp Cloud API. Here’s why and when you
might use this script:

1. Extracting Key Information from Payloads:


When handling WhatsApp Cloud API requests, the incoming payloads (often JSON) contain
important data, like the "from" field that identifies the sender.
This script allows you to extract specific values (in this case, "from") directly from the request
body, making it easier to route or handle requests based on this information.
2. Dynamic Routing and Load Balancing:
HAProxy can use information from HTTP requests to make routing decisions. By registering
`parseElementWhatsAppCloud` as a "fetch" function, HAProxy can extract and use the "from"
value to dynamically route requests to different backend servers or take specific actions
based on who the sender is.
3. Logging and Debugging:
The script includes logging, so you can track incoming payloads and verify the extracted
values. This is helpful for monitoring traffic and troubleshooting if certain fields are missing
or if payloads are malformed.
4. Automating Response and Policy Enforcement:
If you have policies or rules specific to certain senders or message types, you can use the
extracted "from" data to enforce those rules or trigger automated responses directly within
HAProxy.
5. Offloading Parsing to HAProxy:
By performing this parsing at the HAProxy level, you can reduce the load on your application
servers, allowing HAProxy to manage certain aspects of data handling and processing.

Use Cases:

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 4/5
Identify and Route Messages: Based on the "from" field, HAProxy could forward the request to a
particular service or server.
Logging and Auditing: Record which senders are making requests and log their activities.
Filtering or Blocking Requests: If a particular sender should be restricted, HAProxy could use this
function to identify and block or rate-limit requests based on the "from" value.

In summary, you use this script to extract specific fields from incoming HTTP request bodies in HAProxy,
providing flexibility in handling WhatsApp Cloud API traffic and enabling more complex routing, logging,
or filtering capabilities without needing to modify the application server.

Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 5/5

You might also like