Created
November 8, 2023 23:10
-
-
Save vasso123/d7148c60fce42726d04a224f87134ac5 to your computer and use it in GitHub Desktop.
Lua HAProxy example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local http = require("http") | |
core.register_action("auth-request", { "tcp-req", "http-req" }, function(txn) | |
auth_request(txn) | |
end, 0) | |
function set_var_pre_2_2(txn, var, value) | |
return txn:set_var(var, value) | |
end | |
function set_var_post_2_2(txn, var, value) | |
return txn:set_var(var, value, true) | |
end | |
set_var = function(txn, var, value) | |
local success = pcall(set_var_post_2_2, txn, var, value) | |
if success then | |
set_var = set_var_post_2_2 | |
else | |
set_var = set_var_pre_2_2 | |
end | |
return set_var(txn, var, value) | |
end | |
function auth_request(txn) | |
set_var(txn, "txn.auth_response_successful", false) | |
txn:Info("auth_request: start") | |
local auth_backend_name = "ll_auth_server" | |
-- Check whether the given backend exists. | |
if core.backends[auth_backend_name] == nil then | |
txn:Alert("Unknown auth-request backend '" .. auth_backend_name .. "'") | |
set_var(txn, "txn.auth_response_code", 500) | |
return | |
end | |
txn:Info("auth_request: auth backend postoji") | |
-- Check whether the given backend has servers that | |
-- are not `DOWN`. | |
local auth_srv_address_port = nil | |
for name, server in pairs(core.backends[auth_backend_name].servers) do | |
local status = server:get_stats()['status'] | |
if status == "no check" or status:find("UP") == 1 then | |
auth_srv_address_port = server:get_addr() | |
break | |
end | |
end | |
if auth_srv_address_port == nil then | |
txn:Warning("No servers available for auth-request backend: '" .. auth_backend_name .. "'") | |
set_var(txn, "txn.auth_response_code", 500) | |
return | |
end | |
txn:Info("auth_request: auth backend adresa: " .. auth_srv_address_port) | |
local client_ip = txn.f:src() | |
txn:Info("auth_request: client ip: " .. client_ip) | |
local headers = {} | |
local method = "GET" | |
local response, err = http.send(method:upper(), { | |
url = "http://" .. auth_srv_address_port .. "/haproxy?ip_address=" .. client_ip, | |
headers = headers, | |
}) | |
--TODO provjeriti err | |
txn:Info("auth_request: status code: " .. response.status_code) | |
txn:Info("auth_request: content: " .. response.content) | |
if response.content == 'true' then | |
set_var(txn, "txn.auth_response_successful", true) | |
else | |
set_var(txn, "txn.auth_response_successful", false) | |
end | |
txn:Info("auth_request: END") | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment