讓 HaProxy 回應 request IP
haproxy ip -使用 lua 來處理 http request。
Why
藏在很深的內部網路中,有時候想知道對外 IP 是什麼,這就能派上場。
How
寫一個內嵌的 lua 來回應 http request。
範例如下,
pong.lua
local function pong(applet)
  local s = string.format([[{"ip":"%s"}]], applet.f:src()) // (1)
  applet:set_status(200)
  applet:add_header("content-length", string.len(s))
  applet:add_header("content-type", "application/json; charset=utf-8")
  applet:add_header("Access-Control-Allow-Origin", "*")
  applet:start_response()
  applet:send(s)
end
core.register_service("ping", "http", pong)  // (2)
- 
利用 applet 取得 IP
 - 
將服務註冊到 haproxy ,註冊的名字為 ping ,模式為 http。
 
在 haproxy config 中,將上面的 lua 程式設定為特定網址或路徑的 http response。
haproxy.cfg
global
    lua-load <path>/pong.lua  // (1)
frontend ping
  // acl ping path /ping
  // use_backend pong-server if ping
  default_backend pong-server
backend pong-server
    http-request use-service lua.ping  (2)
- 
先載入剛剛寫的 lua 程式
 - 
指定由已經註冊的 lua.ping 程式來回應