Kong插件開發(fā)工具包

Kong插件開發(fā)工具包

插件開發(fā)工具包(或稱 PDK),是一組 Lua 方法和變量,插件可以使用這些方法和變量實(shí)現(xiàn)自己的邏輯,PDK 最初在 Kong 0.14.0 中發(fā)布,PDK 保證從1.0.0版本開始向前兼容,截至本版本,PDK 尚未達(dá)到1.0.0,然而插件作者可以放心依賴它與請求、響應(yīng)或核心組件進(jìn)行安全可靠的交互
用戶可以通過全局變量訪問插件開發(fā)工具包,例如 kong.request、kong.log

kong.version

當(dāng)前 Kong 節(jié)點(diǎn)的版本號,字符串格式
用法:

print(kong.version) -- "0.14.0"

kong.version_num

當(dāng)前 Kong 節(jié)點(diǎn)的版本號,用來做版本比較,整數(shù)格式
用法:

if kong.version_num < 13000 then -- 000.130.00 -> 0.13.0
-- no support for Routes & Services
end

kong.pdk_major_version

當(dāng)前 PDK 的大版本號,整數(shù)格式
用法:

if kong.pdk_version_num < 2 then
-- PDK is below version 2
end

kong.pdk_version

當(dāng)前 PDK 的版本號,字符串格式
用法:

print(kong.pdk_version) -- "1.0.0"

kong.configuration

當(dāng)前 Kong 節(jié)點(diǎn)的配置信息,基于配置文件和環(huán)境變量,文件中以逗號分隔的列表此處顯示為字符串?dāng)?shù)組
用法:

print(kong.configuration.prefix) -- "/usr/local/kong"
-- this table is read-only; the following throws an error:
kong.configuration.prefix = "foo"

kong.db

Kong 的 DAO 實(shí)例(kong.db 模塊),包含對多個實(shí)體的訪問對象
用法:

kong.db.services:insert()
kong.db.routes:select()

kong.dns

Kong 的 DNS 解析器實(shí)例

kong.worker_events

Kong 的 IPC 模塊實(shí)例,用于內(nèi)部 worker 進(jìn)程通信

kong.cluster_events

Kong 的集群事件模塊實(shí)例,用于節(jié)點(diǎn)間通信

kong.cache

Kong 緩存對象實(shí)例

kong.client

Client 模塊是一組方法,通過請求上下文,用于檢索連接到Kong的客戶端的信息

kong.client.get_ip()

返回發(fā)起請求的遠(yuǎn)程 IP 地址,它將始終返回直連到 Kong 的客戶端的地址,所以,當(dāng) Kong 之前有負(fù)載均衡器的情況下,這個方法會返回負(fù)載均衡器的地址,而不是下游客戶端的地址

  • 段:
certificate, rewrite, access, header_filter, body_filter, log
  • 返回值:
    發(fā)起請求的遠(yuǎn)程 IP 地址,字符串格式
  • 用法:
-- Given a client with IP 127.0.0.1 making connection through
-- a load balancer with IP 10.0.0.1 to Kong answering the request for
-- https://example.com:1234/v1/movies
kong.client.get_ip() -- "10.0.0.1"

kong.client.get_forwarded_ip()

返回發(fā)起請求的遠(yuǎn)程 IP 地址,與 kong.client.get_ip 不同,這個方法會考慮到位于 Kong 之前的負(fù)載均衡器以及轉(zhuǎn)發(fā)地址,這個方法是否返回轉(zhuǎn)發(fā)地址取決于幾個 Kong 配置參數(shù):trusted_ips、real_ip_header、real_ip_recursive

  • 段:
certificate, rewrite, access, header_filter, body_filter, log
  • 返回值:
    發(fā)起請求的遠(yuǎn)程 IP 地址,考慮轉(zhuǎn)發(fā)地址,字符串格式
  • 用法:
-- Given a client with IP 127.0.0.1 making connection through
-- a load balancer with IP 10.0.0.1 to Kong answering the request for
-- https://username:password@example.com:1234/v1/movies

kong.request.get_forwarded_ip() -- "127.0.0.1"

-- Note: assuming that 10.0.0.1 is one of the trusted IPs, and that
-- the load balancer adds the right headers matching with the configuration
-- of `real_ip_header`, e.g. `proxy_protocol`.

kong.client.get_port()

返回發(fā)起請求的端口,它將始終返回直連到 Kong 的客戶端的端口,所以,當(dāng) Kong 之前有負(fù)載均衡器的情況下,這個方法會返回負(fù)載均衡器的端口,而不是下游客戶端的端口

  • 段:
certificate, rewrite, access, header_filter, body_filter, log
  • 返回值:
    客戶端端口號,整數(shù)格式
  • 用法:
-- [client]:40000 <-> 80:[balancer]:30000 <-> 80:[kong]:20000 <-> 80:[service]
kong.client.get_port() -- 30000

kong.client.get_forwarded_port()

返回發(fā)起請求的端口,與 kong.client.get_port 不同,這個方法會考慮到位于 Kong 之前的負(fù)載均衡器以及轉(zhuǎn)發(fā)端口,這個方法是否返回轉(zhuǎn)發(fā)端口取決于幾個 Kong 配置參數(shù):trusted_ips、real_ip_header、real_ip_recursive

  • 段:
certificate, rewrite, access, header_filter, body_filter, log
  • 返回值:
    客戶端端口號,考慮轉(zhuǎn)發(fā)端口號,整數(shù)格式
  • 用法:
-- [client]:40000 <-> 80:[balancer]:30000 <-> 80:[kong]:20000 <-> 80:[service]
kong.client.get_forwarded_port() -- 40000

-- Note: assuming that [balancer] is one of the trusted IPs, and that
-- the load balancer adds the right headers matching with the configuration
-- of `real_ip_header`, e.g. `proxy_protocol`.

kong.client.get_credential()

返回當(dāng)前經(jīng)過身份驗(yàn)證的消費(fèi)者的憑證,如果未設(shè)置,返回 nil

  • 段:
access, header_filter, body_filter, log
  • 返回值:
    經(jīng)過身份驗(yàn)證的憑證
  • 用法:
local credential = kong.client.get_credential()
if credential then
consumer_id = credential.consumer_id
else
-- request not authenticated yet
end

kong.client.get_consumer()

返回當(dāng)前經(jīng)過身份驗(yàn)證的消費(fèi)者實(shí)體,如果未設(shè)置,返回 nil

  • 段:
access, header_filter, body_filter, log
  • 返回值:
    經(jīng)過身份驗(yàn)證的消費(fèi)者
  • 用法:
local consumer = kong.client.get_consumer()
if consumer then
consumer_id = consumer.id
else
-- request not authenticated yet, or a credential
-- without a consumer (external auth)
end

kong.client.authenticate(consumer, credential)

為當(dāng)前請求設(shè)置經(jīng)過身份驗(yàn)證的消費(fèi)者或憑證,消費(fèi)者和憑證必須存在一個,否則方法將報錯

  • 段:
access
  • 參數(shù):
    consumer(table|nil):設(shè)置消費(fèi)者,如果不設(shè)置值,之前存在的值會被清空
    credential(table|nil):設(shè)置憑證,如果不設(shè)置值,之前存在的值會被清空
  • 用法:
-- assuming `credential` and `consumer` have been set by some authentication code
kong.client.authenticate(consumer, credentials)

kong.client.get_protocol(allow_terminated)

返回當(dāng)前路由匹配的協(xié)議,如果沒有路由匹配,返回 nil

  • 段:
access, header_filter, body_filter, log
  • 參數(shù):
    allow_terminated:布爾值,如果設(shè)置,則在檢查 https 時檢查 X-Forwarded-Proto
  • 返回值:
  1. string | nil:"http"、"https"、"tcp"、"tls" 或 nil
  2. nil | err:成功返回 nil,失敗返回錯誤信息
  • 用法:
kong.client.get_protocol() -- "http"

kong.ctx

當(dāng)前請求上下文

kong.ctx.shared

一個 table 結(jié)構(gòu)的數(shù)據(jù),它用于在給定請求的多個插件之間共享數(shù)據(jù),由于它只與請求的上下文相關(guān),所有無法從 Lua 模塊的頂級塊訪問此表,只能在請求段中訪問,對應(yīng)插件的 rewriteaccess、header_filterbody_filterlog 接口
所有插件都可以看到單個插件在此 table 中插入的值,與其加護(hù)時必須謹(jǐn)慎,因?yàn)槊麤_突會導(dǎo)致數(shù)據(jù)被覆蓋

  • 段:
rewrite, access, header_filter, body_filter, log
  • 用法:
-- Two plugins A and B, and if plugin A has a higher priority than B's
-- (it executes before B):

-- plugin A handler.lua
function plugin_a_handler:access(conf)
kong.ctx.shared.foo = "hello world"

kong.ctx.shared.tab = {
bar = "baz"
}
end

-- plugin B handler.lua
function plugin_b_handler:access(conf)
kong.log(kong.ctx.shared.foo) -- "hello world"
kong.log(kong.ctx.shared.tab.bar) -- "baz"
end

kong.ctx.plugin

一個 table 結(jié)構(gòu)的數(shù)據(jù),與 kong.ctx.shared 不同,此 table 不在插件之間共享,相反,它僅對當(dāng)前插件實(shí)例可見,也就是說,如果配置了多個限流插件實(shí)例(在不同的服務(wù)上),每個實(shí)例對于每個請求都有自己的 table
由于它自帶命名空間,所以它比 kong.ctx.shared 更安全,因?yàn)樗苊饬藵撛诘拿麤_突,這可能導(dǎo)致多個插件在不知不覺中覆蓋了彼此的數(shù)據(jù)

  • 段:
rewrite, access, header_filter, body_filter, log
  • 用法:
-- plugin handler.lua

function plugin_handler:access(conf)
kong.ctx.plugin.val_1 = "hello"
kong.ctx.plugin.val_2 = "world"
end

function plugin_handler:log(conf)
local value = kong.ctx.plugin.val_1 .. " " .. kong.ctx.plugin.val_2

kong.log(value) -- "hello world"
end

kong.ip

此模塊根據(jù) trusted_ips 配置確定給定的 IP 是否可信

kong.ip.is_trusted(address)

根據(jù) trusted_ips 配置屬性,此方法將返回給定的 IP 是否可信,并且是否同時支持 ipv4 和 ipv6

  • 段:
init_worker, certificate, rewrite, access, header_filter, body_filter, log
  • 參數(shù):
    address(string):IP 地址
  • 返回值:
    true 代表受信,false代表不受信,布爾格式
  • 用法:
if kong.ip.is_trusted("1.1.1.1") then
kong.log("The IP is trusted")
end

kong.log

一個 table 結(jié)構(gòu)的數(shù)據(jù),此命名空間包含了日志工具的實(shí)例,含有下述所有方法,每個插件的實(shí)例有單獨(dú)的命名空間,Kong 確保在執(zhí)行插件之前,會將實(shí)例與專用于插件的日志工具交換,這允許日志以插件的名稱作為前綴,以便進(jìn)行調(diào)試

kong.log(…)

日志使用當(dāng)前 Nginx 配置中的 error_log 指令,日志級別是 notice,Nginx 的 error_log 指令通過 log_levelproxy_error_logadmin_error_log 這三個配置設(shè)置
傳入此方法的參數(shù)的拼接方式與 ngx.log() 類似,日志中將顯示調(diào)用它的 Lua 文件和行號,與 ngx.log() 不同,此方法將使用 [kong],而不是 [lua],作為錯誤消息的前綴,參數(shù)可以是任何格式的,在打印日志時會調(diào)用 tostring 方法轉(zhuǎn)換成字符串格式
核心生成的日志格式:

[kong] %file_src:%line_src %message

相比較,插件生成的日志格式:

[kong] %file_src:%line_src [%namespace] %message
  1. %file_src:調(diào)用日志的文件名
  2. %func_name:調(diào)用日志的方法的名稱
  3. %line_src:調(diào)用日志的行號
  4. %message:日志消息

示例,調(diào)用下列方法:

kong.log("hello ", "world")

核心打印日志:

2017/07/09 19:36:25 [notice] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

插件打印日志:

2017/07/09 19:36:25 [notice] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"
  • 段:
init_worker, certificate, rewrite, access, header_filter, body_filter, log
  • 參數(shù):
    在發(fā)送到日志之前,所有的參數(shù)會拼接到一起連成字符串
  • 返回值:
    沒有返回,無效的輸入拋錯
  • 用法:
kong.log("hello ", "world") -- alias to kong.log.notice()

kong.log.LEVEL(…)

kong.log() 類似,但生成的日志具有 \<level\> 日志級別,而不是 notice,支持的日志級別包括:
kong.log.alert()
kong.log.crit()
kong.log.err()
kong.log.warn()
kong.log.notice()
kong.log.info()
kong.log.debug()
記錄日志的語法與 kong.log() 類似,例如:

kong.log.err("hello ", "world")

在核心內(nèi)會生成一條日志,如下:

2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"

如果從插件中調(diào)用(例如 key-auth),它將包含命名空間前綴,如下:

2017/07/09 19:36:25 [error] 25932#0: *1 [kong] some_file.lua:54 [key-auth] hello world, client: 127.0.0.1, server: localhost, request: "GET /log HTTP/1.1", host: "localhost"
  • 段:
init_worker, certificate, rewrite, access, header_filter, body_filter, log
  • 參數(shù):
    在發(fā)送到日志之前,所有的參數(shù)會拼接到一起連成字符串
  • 返回值:
    沒有返回,無效的輸入拋錯
  • 用法:
kong.log.warn("something require attention")
kong.log.err("something failed: ", err)
kong.log.alert("something requires immediate action")

kong.log.inspect(…)

kong.log() 類似,此方法會生成 notice 級別的日志,并且可以接受任意數(shù)量的參數(shù),如果通過 kong.log.inspect.off() 方法禁用了功能,那么此方法不會打印任何內(nèi)容

kong.log.inspect("...")

kong.log() 不同的是,該方法會在拼接參數(shù)時加上空格,這個方法主要用于調(diào)試,應(yīng)避免在生產(chǎn)代碼中使用,因?yàn)樗鼒?zhí)行了很多格式化操作,消耗資源
kong.log.inspect(…) 的日志格式如下:

%file_src:%func_name:%line_src %message
  1. %file_src:調(diào)用日志的文件名
  2. %func_name:調(diào)用日志的方法的名稱
  3. %line_src:調(diào)用日志的行號
  4. %message:日志消息
  • 段:
init_worker, certificate, rewrite, access, header_filter, body_filter, log
  • 參數(shù):
    在發(fā)送到日志之前,所有的參數(shù)會拼接到一起連成字符串
  • 用法:
kong.log.inspect("some value", a_variable)

kong.log.inspect.on()

啟用 inspect 日志功能

  • 段:
init_worker, certificate, rewrite, access, header_filter, body_filter, log
  • 用法:
kong.log.inspect.on()

kong.log.inspect.off()

禁用 notice 日志功能

  • 段:
init_worker, certificate, rewrite, access, header_filter, body_filter, log
  • 用法:
kong.log.inspect.off()

kong.nginx

Nginx 信息模塊,一組用于檢索 Nginx 實(shí)現(xiàn)細(xì)節(jié)和元信息的方法

kong.nginx.get_subsystem()

  • 段:
any
  • 返回值:
    httpstream,字符串格式
  • 用法:
kong.nginx.get_subsystem() -- "http"

kong.node

節(jié)點(diǎn)級別信息

kong.node.get_id()

返回此節(jié)點(diǎn)用于描述自身的 ID

  • 返回值:
    節(jié)點(diǎn) ID,字符串格式
  • 用法:
local id = kong.node.get_id()

kong.node.get_memory_stats([unit[, scale]])

返回該節(jié)點(diǎn)的內(nèi)存使用數(shù)據(jù)

  • 參數(shù):
    unit(string, optional):內(nèi)存計(jì)量單位,可以是 b/B、k/K、m/M 或 g/G
    scale(number, optional):精度,默認(rèn)小數(shù)點(diǎn)后兩位
  • 返回值:
    包含此節(jié)點(diǎn)的內(nèi)存使用統(tǒng)計(jì)數(shù)據(jù),如果單位是 b/B(默認(rèn)值),則值為數(shù)字,否則統(tǒng)計(jì)數(shù)據(jù)為字符串,后綴是單位,table 格式
  • 用法:
local res = kong.node.get_memory_stats()
-- res will have the following structure:
{
  lua_shared_dicts = {
    kong = {
      allocated_slabs = 12288,
      capacity = 24576
    },
    kong_db_cache = {
      allocated_slabs = 12288,
      capacity = 12288
    }
  },
  workers_lua_vms = {
    {
      http_allocated_gc = 1102,
      pid = 18004
    },
    {
      http_allocated_gc = 1102,
      pid = 18005
    }
  }
}

local res = kong.node.get_memory_stats("k", 1)
-- res will have the following structure:
{
  lua_shared_dicts = {
    kong = {
      allocated_slabs = "12.0 KiB",
      capacity = "24.0 KiB",
    },
    kong_db_cache = {
      allocated_slabs = "12.0 KiB",
      capacity = "12.0 KiB",
    }
  },
  workers_lua_vms = {
    {
      http_allocated_gc = "1.1 KiB",
      pid = 18004
    },
    {
      http_allocated_gc = "1.1 KiB",
      pid = 18005
    }
  }
}

kong.request

一組方法,用于獲取客戶端發(fā)出的請求信息

kong.request.get_scheme()

返回請求 URL 的 schema 組件,返回值為小寫格式

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    http 或者 https,字符串格式
  • 用法:
-- Given a request to https://example.com:1234/v1/movies
kong.request.get_scheme() -- "https"

kong.request.get_host()

返回請求 URL 的 host 組件,或者 Host 頭的值,返回值為小寫格式

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    主機(jī)地址,字符串格式
  • 用法:
-- Given a request to https://example.com:1234/v1/movies
kong.request.get_host() -- "example.com"

kong.request.get_port()

返回請求 URL 的 port 組件

  • 段:
certificate, rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    端口號,整數(shù)格式
  • 用法:
-- Given a request to https://example.com:1234/v1/movies
kong.request.get_port() -- 1234

kong.request.get_forwarded_scheme()

返回請求 URL 的 schema 組件,如果請求來自可信源,也會考慮 X-Forwarded-Proto 請求頭,返回值為小寫格式,該方法是否考慮 X-Forwarded-Proto 請求頭取決于幾個 Kong 配置參數(shù):trusted_ips、real_ip_header、real_ip_recursive

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    轉(zhuǎn)發(fā)的 schema,字符串格式
  • 用法:
kong.request.get_forwarded_scheme()  -- "https"

kong.request.get_forwarded_host()

返回請求 URL 的 host 組件,不同于 kong.request.get_host(),如果請求來自可信源,也會考慮 X-Forwarded-Host 請求頭,該方法是否考慮 X-Forwarded-Host 請求頭取決于幾個 Kong 配置參數(shù):trusted_ips、real_ip_header、real_ip_recursive

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    轉(zhuǎn)發(fā)的主機(jī)地址,字符串格式
  • 用法:
kong.request.get_forwarded_host()  -- "example.com"

kong.request.get_forwareded_port()

返回請求 URL 的 port 組件,如果請求來自可信源,也會考慮 X-Forwarded-Host 請求頭,該方法是否考慮 X-Forwarded-Proto 請求頭取決于幾個 Kong 配置參數(shù):trusted_ips、real_ip_header、real_ip_recursive

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    轉(zhuǎn)發(fā)的端口,整數(shù)格式
  • 用法:
kong.request.get_forwarded_port()  -- 1234

kong.request.get_http_version()

返回 Http 協(xié)議使用的版本號,返回值為 1.12.0

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    字符串類型,或者是 nil
  • 用法:
kong.request.get_http_version()  -- "1.1"

kong.request.get_method()

返回請求的 Http 方法,返回值為大寫格式

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    請求方法,字符串格式
  • 用法:
kong.request.get_method()  -- "GET"

kong.request.get_path()

返回請求 URL 的 path 組件,不包含請求參數(shù)

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    請求路徑,字符串格式
  • 用法:
-- Given a request to https://example.com:1234/v1/movies?movie=foo
kong.request.get_path() -- "/v1/movies"

kong.request.get_path_with_query()

返回請求 URL 的 path 組件,包含請求參數(shù)

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    請求路徑,包含請求參數(shù),字符串格式
  • 用法:
-- Given a request to https://example.com:1234/v1/movies?movie=foo
kong.request.get_path_with_query() -- "/v1/movies?movie=foo"

kong.request.get_raw_query()

返回請求 URL 的 query 組件,不包含 ? 字符

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    請求參數(shù)
  • 用法:
-- Given a request to https://example.com/foo?msg=hello%20world&bla=&bar
kong.request.get_raw_query() -- "msg=hello%20world&bla=&bar"

kong.request.get_query_arg()

返回從當(dāng)前請求的查詢參數(shù)獲取的指定參數(shù)的值,如果參數(shù)有值,返回的是字符串或者布爾類型,如果找不到參數(shù),返回 nil,如果查詢參數(shù)中多次出現(xiàn)具有相同名稱的參數(shù),該方法返回第一次出現(xiàn)的值

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 返回值:
    請求參數(shù),字符串類型、布爾類型、nil
  • 用法:
-- Given a request GET /test?foo=hello%20world&bar=baz&zzz&blo=&bar=bla&bar
kong.request.get_query_arg("foo") -- "hello world"
kong.request.get_query_arg("bar") -- "baz"
kong.request.get_query_arg("zzz") -- true
kong.request.get_query_arg("blo") -- ""

kong.request.get_query([max_args])

返回從請求參數(shù)提取的參數(shù)表,鍵是參數(shù)名稱,值是參數(shù)值,鍵和值都未經(jīng)轉(zhuǎn)義,默認(rèn)情況下,這個方法返回100個參數(shù),可以指定 max_args 調(diào)整這個值,參數(shù)范圍是1至1000

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 參數(shù):
    max_args(number, optional):參數(shù)表的最大個數(shù)
  • 返回值:
    請求參數(shù),table 格式
  • 用法:
-- Given a request GET /test?foo=hello%20world&bar=baz&zzz&blo=&bar=bla&bar
for k, v in pairs(kong.request.get_query()) do
  kong.log.inspect(k, v)
end
-- Will print
-- "foo" "hello world"
-- "bar" {"baz", "bla", true}
-- "zzz" true
-- "blo" ""

kong.request.get_header(name)

返回請求頭的值,請求頭名不區(qū)分大小寫,并全部采用小寫形式,- 可以寫成 _,比如 X-Custom-Header 可以寫成 x_custom_header

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 參數(shù):
    name(string):請求頭的名稱
  • 返回值:
    請求頭的值,字符串類型或者 nil
  • 用法:
-- Given a request with the following headers:
-- Host: foo.com
-- X-Custom-Header: bla
-- X-Another: foo bar
-- X-Another: baz
kong.request.get_header("Host")            -- "foo.com"
kong.request.get_header("x-custom-header") -- "bla"
kong.request.get_header("X-Another")       -- "foo bar"

kong.request.get_headers([max_headers])

返回請求頭表,鍵是請求頭名,值是請求頭值,默認(rèn)情況下,這個方法返回100個請求頭,可以指定 max_headers 調(diào)整這個值,參數(shù)范圍是1至1000

  • 段:
rewrite, access, header_filter, body_filter, log, admin_api
  • 參數(shù):
    max_headers(number, optional):請求頭表的最大個數(shù)
  • 返回值:
    請求頭,table 格式
  • 用法:
-- Given a request with the following headers:
-- Host: foo.com
-- X-Custom-Header: bla
-- X-Another: foo bar
-- X-Another: baz
local headers = kong.request.get_headers()
headers.host            -- "foo.com"
headers.x_custom_header -- "bla"
headers.x_another[1]    -- "foo bar"
headers["X-Another"][2] -- "baz"

kong.request.get_raw_body()

返回請求體,如果請求體沒有內(nèi)容,該方法返回一個空字符串,如果請求體大小大于 Nginx 緩沖區(qū)大小(通過 client_body_buffer_size 設(shè)置),該方法會失敗并返回錯誤信息

  • 段:
rewrite, access, admin_api
  • 返回值:
    請求體,字符串格式
  • 用法:
-- Given a body with payload "Hello, Earth!":
kong.request.get_raw_body():gsub("Earth", "Mars") -- "Hello, Mars!"

kong.request.get_body([mimetype[, max_args]])

以鍵值對形式返回請求體數(shù)據(jù),請求體以最合適的格式解析:

  1. 如果指定了 mimetype,根據(jù) content type 對請求體進(jìn)行解碼
  2. 如果 content type 是 application/x-www-form-urlencoded,以 form-encoded 形式返回請求體
  3. 如果 content type 是 multipart/form-data,以上述方式解析,multipart(kong.request.get_raw_body(), kong.request.get_header("Content-Type")):get_all()
  4. 如果 content type 是 application/json,以 JSON 形式解析請求體,JSON 格式對應(yīng) Lua 的基本類型
  5. 如果不是上述情況,返回 nil 表示請求未被解析
    mimetype 可以取以下值:application/x-www-form-urlencoded、application/jsonmultipart/form-data
    max_args 限定 application/x-www-form-urlencoded 解析參數(shù)的個數(shù)
  • 段:
rewrite, access, admin_api
  • 參數(shù):
    mimetype(string, optional):mimetype
    max_args(number, optional):請求體表的最大個數(shù)
  • 返回值:
  1. 請求體,table 格式或 nil
  2. 錯誤信息,table 格式或 nil
  3. mimetype 類型,table 格式或 nil
  • 用法:
local body, err, mimetype = kong.request.get_body()
body.name -- "John Doe"
body.age  -- "42"

kong.response

響應(yīng)模塊,其中包含了一組方法,用于生成和操作發(fā)送發(fā)送給客戶端的響應(yīng),響應(yīng)可以由 Kong 生成,或者從服務(wù)的響應(yīng)體中代理過來

kong.response.get_status()

返回當(dāng)前為下游響應(yīng)設(shè)置的的 Http 狀態(tài)碼,如果請求被代理,則返回值將是來自 Service 的響應(yīng)值(與 kong.service.response.get_status() 相同),如果請求未被代理,并且響應(yīng)是由 Kong 本身產(chǎn)生的(比如通過 kong.response.exit()),則返回值將按原樣返回

  • 段:
header_filter, body_filter, log, admin_api
  • 返回值:
    為下游響應(yīng)設(shè)置的 Http 狀態(tài)碼
  • 用法:
kong.response.get_status()  -- 200

kong.response.get_header(name)

返回指定響應(yīng)頭的值,該函數(shù)包含來自代理服務(wù)的響應(yīng)頭和 Kong 添加的響應(yīng)頭(例如,通過 kong.response.add_header()

  • 段:
header_filter, body_filter, log, admin_api
  • 參數(shù):
    name(string):請求頭的名稱,請求頭名不區(qū)分大小寫,并全部采用小寫形式,- 可以寫成 _,比如 X-Custom-Header 可以寫成 x_custom_header
  • 返回值:
    響應(yīng)頭的值,字符串格式或 nil
  • 用法:
-- Given a response with the following headers:
-- X-Custom-Header: bla
-- X-Another: foo bar
-- X-Another: baz

kong.response.get_header("x-custom-header") -- "bla"
kong.response.get_header("X-Another")       -- "foo bar"
kong.response.get_header("X-None")          -- nil

kong.response.get_headers([max_headers])

包含響應(yīng)頭的 Lua table,與 kong.service.response.get_headers() 不同,該方法會返回客戶端接收到的所有響應(yīng)頭,包括 Kong 本身添加的響應(yīng)有,默認(rèn)情況下,該方法最多返回100個響應(yīng)頭,可以指定 max_headers 調(diào)整這個值,參數(shù)范圍是1至1000

  • 段:
header_filter, body_filter, log, admin_api
  • 參數(shù):
    max_headers(number, optional):
  • 返回值:
  1. 響應(yīng)中的響應(yīng)頭 table,table 格式
  2. 如果響應(yīng)頭數(shù)目超過 max_headers,返回 truncated,字符串格式
  • 用法:
-- Given an response from the Service with the following headers:
-- X-Custom-Header: bla
-- X-Another: foo bar
-- X-Another: baz

local headers = kong.response.get_headers()

headers.x_custom_header -- "bla"
headers.x_another[1]    -- "foo bar"
headers["X-Another"][2] -- "baz"

kong.response.get_source()

這個方法確定當(dāng)前響應(yīng)的來源,返回值可能包含三類字符串:

  1. exit:調(diào)用了 kong.response.exit(),即請求被插件或 Kong 本身短路的時候
  2. error:發(fā)生錯誤,比如連接到上游服務(wù)超時,返回 error
  3. service:連接到代理服務(wù),返回 service
  • 段:
header_filter, body_filter, log, admin_api
  • 返回值:
    響應(yīng)源,字符串格式
  • 用法:
if kong.response.get_source() == "service" then
  kong.log("The response comes from the Service")
elseif kong.response.get_source() == "error" then
  kong.log("There was an error while processing the request")
elseif kong.response.get_source() == "exit" then
  kong.log("There was an early exit while processing the request")
end

kong.response.set_status(status)

更改 Http 狀態(tài)碼,這個方法應(yīng)該在 header_filter 段中使用,此時 Kong 準(zhǔn)備將響應(yīng)頭發(fā)送回客戶端

  • 段:
rewrite, access, header_filter, admin_api
  • 參數(shù):
    status(number):新的 Http 狀態(tài)碼
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.response.set_status(404)

kong.response.set_header(name, value)

設(shè)置響應(yīng)頭,會覆蓋已經(jīng)存在的響應(yīng)頭,這個方法應(yīng)該在 header_filter 段中使用,此時 Kong 準(zhǔn)備將響應(yīng)頭發(fā)送回客戶端

  • 段:
rewrite, access, header_filter, admin_api
  • 參數(shù):
    name(string): 響應(yīng)頭的名稱
    value(string,number,boolean):響應(yīng)頭的值
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.response.set_header("X-Foo",  "value")

kong.response.add_header(name, value)

設(shè)置響應(yīng)頭,與 kong.response.set_header() 不同,這個方法不會覆蓋已經(jīng)存在的響應(yīng)頭,另外相同的響應(yīng)頭可以繼續(xù)添加在響應(yīng)中,這個方法應(yīng)該在 header_filter 段中使用,此時 Kong 準(zhǔn)備將響應(yīng)頭發(fā)送回客戶端

  • 段:
rewrite, access, header_filter, admin_api
  • 參數(shù):
    name(string): 響應(yīng)頭的名稱
    value(string,number,boolean):響應(yīng)頭的值
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.response.add_header("Cache-Control", "no-cache")
kong.response.add_header("Cache-Control", "no-store")

kong.response.clear_header(name)

刪除響應(yīng)頭,這個方法應(yīng)該在 header_filter 段中使用,此時 Kong 準(zhǔn)備將響應(yīng)頭發(fā)送回客戶端

  • 段:
rewrite, access, header_filter, admin_api
  • 參數(shù):
    name(string): 需要清除的響應(yīng)頭的名稱
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.response.set_header("X-Foo", "foo")
kong.response.add_header("X-Foo", "bar")

kong.response.clear_header("X-Foo")
-- from here onwards, no X-Foo headers will exist in the response

kong.response.set_headers(headers)

設(shè)置響應(yīng)頭,與 kong.response.set_header() 不同,headers 參數(shù)是一個 table,鍵是字符串格式,值是字符串或字符串?dāng)?shù)組,這個方法應(yīng)該在 header_filter 段中使用,此時 Kong 準(zhǔn)備將響應(yīng)頭發(fā)送回客戶端,此方法會覆蓋已經(jīng)存在的響應(yīng)頭

  • 段:
rewrite, access, header_filter, admin_api
  • 參數(shù):
    headers(table)
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.response.set_headers({
  ["Bla"] = "boo",
  ["X-Foo"] = "foo3",
  ["Cache-Control"] = { "no-store", "no-cache" }
})

-- Will add the following headers to the response, in this order:
-- X-Bar: bar1
-- Bla: boo
-- Cache-Control: no-store
-- Cache-Control: no-cache
-- X-Foo: foo3

kong.response.exit(status[, body[, headers]])

  • 段:
rewrite, access, admin_api, header_filter (僅當(dāng) body 為 nil 時)
  • 參數(shù):
  1. status(number):Http 狀態(tài)碼
  2. body(table,string,optional):響應(yīng)體
  3. headers(table,optional):響應(yīng)頭
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
return kong.response.exit(403, "Access Forbidden", {
  ["Content-Type"] = "text/plain",
  ["WWW-Authenticate"] = "Basic"
})

---

return kong.response.exit(403, [[{"message":"Access Forbidden"}]], {
  ["Content-Type"] = "application/json",
  ["WWW-Authenticate"] = "Basic"
})

---

return kong.response.exit(403, { message = "Access Forbidden" }, {
  ["WWW-Authenticate"] = "Basic"
})

kong.router

route 模塊包含一組方法,用于訪問請求的路由屬性

kong.router.get_route()

返回路由實(shí)體,請求與此路由匹配

  • 段:
access, header_filter, body_filter, log
  • 返回值:
    路由實(shí)體,table 格式
  • 用法:
if kong.router.get_route() then
  -- routed by route & service entities
else
  -- routed by a legacy API entity
end

kong.router.get_service()

返回當(dāng)前服務(wù)實(shí)體,請求會路由到這個服務(wù)上

  • 段:
access, header_filter, body_filter, log
  • 返回值:
    服務(wù)實(shí)體,table 格式
  • 用法:
if kong.router.get_service() then
  -- routed by route & service entities
else
  -- routed by a legacy API entity
end

kong.service

service 模塊包含一組方法,用于操作請求連接到服務(wù)上的屬性,比如連接的主機(jī),IP 地址或端口,用于負(fù)載均衡和健康檢查的 upstream 實(shí)體

kong.service.set_upstream(host)

設(shè)置所需的 upstream 實(shí)體處理請求的負(fù)載均衡,使用此方法相當(dāng)于創(chuàng)建一個配置了 host 屬性的服務(wù),并關(guān)聯(lián)到了相應(yīng)的 upstream 實(shí)體(這種情況下,請求將代理到綁定到這個 upstream 的 target 上)
host 參數(shù)接收一個字符串,字符串內(nèi)容需要與配置的 upstream 實(shí)體一致

  • 段:
access
  • 參數(shù):
    host(string)
  • 返回值:
  1. 成功返回 true,沒有找到 upstream 實(shí)體返回 nil
  2. 錯誤發(fā)生時返回字符串格式的錯誤,沒有返回 nil
  • 用法:
local ok, err = kong.service.set_upstream("service.prod")
if not ok then
  kong.log.err(err)
  return
end

kong.service.set_target(host, port)

設(shè)置代理該請求的主機(jī)和端口地址,使用這個方法相當(dāng)于要求 Kong 在接收請求時不執(zhí)行負(fù)載均衡階段,而是手動覆蓋它,這個請求還會忽略重試和健康檢查等負(fù)載均衡組件,host 參數(shù)為字符串格式,是一個(IPv4/IPv6地址),port 參數(shù)為端口號

  • 段:
access
  • 參數(shù):
    host(string)
    port(number)
  • 用法:
kong.service.set_target("service.local", 443)
kong.service.set_target("192.168.130.1", 80)

kong.service.set_tls_cert_key(chain, key)

設(shè)置與服務(wù)器端握手時使用的客戶端證書,chain 參數(shù)是由 ngx.ssl.parse_pem_cert 等方法返回的客戶端證書和中間鏈,key 參數(shù)是與 ngx.ssl.parse_pem_priv_key 等方法返回的客戶端證書對應(yīng)的私鑰

  • 段:
rewrite, access, balancer
  • 參數(shù):
    chain(cdata):客戶端證書鏈
    key(cdata):客戶端證書私鑰
  • 返回值:
  1. 操作成功返回 true,發(fā)生錯誤返回 nil
  2. 錯誤發(fā)生時返回字符串格式的錯誤,沒有返回 nil
  • 用法:
local chain = assert(ssl.parse_pem_cert(cert_data))
local key = assert(ssl.parse_pem_priv_key(key_data))

local ok, err = tls.set_cert_key(chain, key)
if not ok then
  -- do something with error
end

kong.service.request

操作連接上服務(wù)的請求

kong.service.request.set_scheme(scheme)

在將請求路由到服務(wù)時設(shè)置 Http 協(xié)議

  • 段:
access
  • 參數(shù):
    schema(string):Http 協(xié)議,支持 httphttps
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_scheme("https")

kong.service.request.set_path(path)

設(shè)置請求路徑,不包含請求參數(shù)

  • 段:
access
  • 參數(shù):
    path(string):請求路徑
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_path("/v2/movies")

kong.service.request.set_raw_query(query)

設(shè)置請求參數(shù),query 參數(shù)是字符串格式(不包含 ? 字符),并且不會以任何方式處理,更高階的設(shè)置請求參數(shù)方法參考 kong.service.request.set_query()

  • 段:
rewrite,access
  • 參數(shù):
    query(string):原生的請求參數(shù)
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_raw_query("zzz&bar=baz&bar=bla&bar&blo=&foo=hello%20world")

kong.service.request.set_method(method)

設(shè)置 Http 方法

  • 段:
rewrite,access
  • 參數(shù):
    method(string):Http 方法,需要大小,支持的方法有:GETHEAD、PUTPOST、DELETE、OPTIONSMKCOL、COPY、MOVE、PROPFIND、PROPPATCH、LOCKUNLOCK、PATCH、TRACE
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_method("DELETE")

kong.service.request.set_query(args)

設(shè)置請求參數(shù),與 kong.service.request.set_raw_query() 不同,args 參數(shù)必須是 table 格式,鍵是字符串類型,值可以是布爾值、字符串或數(shù)組,所有字符串都進(jìn)行 URL 編碼,生成的查詢字符串根據(jù)字典順序排序,保留同一鍵內(nèi)的值順序,如果需要進(jìn)一步控制生成請求參數(shù),可以使用 kong.service.request.set_raw_query() 方法

  • 段:
rewrite,access
  • 參數(shù):
    args(table):
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_query({
  foo = "hello world",
  bar = {"baz", "bla", true},
  zzz = true,
  blo = ""
})
-- Will produce the following query string:
-- bar=baz&bar=bla&bar&blo=&foo=hello%20world&zzz

kong.service.request.set_header(header, value)

設(shè)置請求頭,會覆蓋已經(jīng)存在的請求頭,如果 header 參數(shù)是 host(大小寫不敏感),會同時設(shè)置請求的 SNI

  • 段:
rewrite,access
  • 參數(shù):
    header(string):請求頭名稱
    value(string,boolean,number):請求頭值
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_header("X-Foo",  "value")

kong.service.request.add_header(header, value)

設(shè)置請求頭,與 kong.service.request.set_header() 不同,不會覆蓋已經(jīng)存在的請求頭

  • 段:
rewrite,access
  • 參數(shù):
    header(string):請求頭名稱
    value(string,boolean,number):請求頭值
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.add_header("Cache-Control", "no-cache")
kong.service.request.add_header("Cache-Control", "no-store")

kong.service.request.clear_header(header)

清除請求頭

  • 段:
rewrite,access
  • 參數(shù):
    header(string):請求頭名稱
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_header("X-Foo", "foo")
kong.service.request.add_header("X-Foo", "bar")
kong.service.request.clear_header("X-Foo")
-- from here onwards, no X-Foo headers will exist in the request

kong.service.request.set_headers(headers)

設(shè)置請求頭,與 kong.service.request.set_header() 不同,headers 參數(shù)必須是 table 格式的

  • 段:
rewrite,access
  • 參數(shù):
    headers(table):table 格式的請求頭集合
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_header("X-Foo", "foo1")
kong.service.request.add_header("X-Foo", "foo2")
kong.service.request.set_header("X-Bar", "bar1")
kong.service.request.set_headers({
  ["X-Foo"] = "foo3",
  ["Cache-Control"] = { "no-store", "no-cache" },
  ["Bla"] = "boo"
})

-- Will add the following headers to the request, in this order:
-- X-Bar: bar1
-- Bla: boo
-- Cache-Control: no-store
-- Cache-Control: no-cache
-- X-Foo: foo3

kong.service.request.set_raw_body(body)

設(shè)置請求體,body 參數(shù)必須是一個字符串,不會以任何方式處理處理,這個方法還會添加 Content-Length 頭,如果想設(shè)置空請求體,直接設(shè)置空字符串,更高階的設(shè)置參考 kong.service.request.set_body()

  • 段:
rewrite,access
  • 參數(shù):
    body(string):原始 body 請求體
  • 返回值:
    無;無效的輸入拋出錯誤
  • 用法:
kong.service.request.set_raw_body("Hello, world!")

kong.service.request.set_body(args[, mimetype])

設(shè)置請求體,與 kong.service.request.set_body() 不同,args 必須是 table 格式,并且以 MIME type 格式編碼

  1. 如果 MIME type 是 application/x-www-form-urlencoded
    以 form-encoded 方式對參數(shù)進(jìn)行編碼
  2. 如果 MIME type 是 multipart/form-data
    以 multipart form data 方式對參數(shù)進(jìn)行編碼
  3. 如果 MIME type 是 application/json
    以 JSON 格式對參數(shù)進(jìn)行編碼
  • 段:
rewrite,access
  • 參數(shù):
    args(table):請求體參數(shù),會轉(zhuǎn)化成相應(yīng)的格式
    mimetype(string,optional)
  • 返回值:
  1. 成功返回 true,失敗返回 nil
  2. 錯誤返回失敗信息,成果返回 nil
  • 用法:
kong.service.set_header("application/json")
local ok, err = kong.service.request.set_body({
  name = "John Doe",
  age = 42,
  numbers = {1, 2, 3}
})

-- Produces the following JSON body:
-- { "name": "John Doe", "age": 42, "numbers":[1, 2, 3] }

local ok, err = kong.service.request.set_body({
  foo = "hello world",
  bar = {"baz", "bla", true},
  zzz = true,
  blo = ""
}, "application/x-www-form-urlencoded")

-- Produces the following body:
-- bar=baz&bar=bla&bar&blo=&foo=hello%20world&zzz

kong.service.response

操作服務(wù)的響應(yīng)

kong.service.response.get_status()

從服務(wù)返回的響應(yīng)的 Http 狀態(tài)碼

  • 段:
header_filter, body_filter, log
  • 返回值:
    從服務(wù)返回的響應(yīng)的 Http 狀態(tài)碼,整數(shù)格式;如果請求未被代理,返回 nil
  • 用法:
kong.log.inspect(kong.service.response.get_status())  -- 418

kong.service.response.get_headers([max_headers])

包含響應(yīng)頭的 Lua table,與 kong.response.get_headers() 不同,該方法僅會返回服務(wù)返回的響應(yīng)中的請求頭(忽略 Kong 本身添加的),如果請求未被代理到任何服務(wù)(比如被鑒權(quán)插件拒絕了并且產(chǎn)生了401響應(yīng)),headers 值是 nil,因?yàn)榉?wù)沒有任何響應(yīng),默認(rèn)情況下,該方法最多返回100個響應(yīng)頭,可以指定 max_headers 調(diào)整這個值,參數(shù)范圍是1至1000

  • 段:
header_filter, body_filter, log
  • 參數(shù):
    max_header(number, optional):
  • 返回值:
  1. 響應(yīng)頭,table 格式
  2. 如果響應(yīng)頭數(shù)目超過 max_headers,返回 truncated,字符串格式
  • 用法:
-- Given a response with the following headers:
-- X-Custom-Header: bla
-- X-Another: foo bar
-- X-Another: baz
local headers = kong.service.response.get_headers()
if headers then
  kong.log.inspect(headers.x_custom_header) -- "bla"
  kong.log.inspect(headers.x_another[1])    -- "foo bar"
  kong.log.inspect(headers["X-Another"][2]) -- "baz"
end

kong.service.response.get_header(name)

返回指定響應(yīng)頭的值,與 kong.response.get_header() 不同,這個方法只會返回服務(wù)的響應(yīng)中的請求頭(忽略 Kong 本身添加的)

  • 段:
header_filter, body_filter, log
  • 參數(shù):
    name(string):響應(yīng)頭的名稱
  • 返回值:
    指定響應(yīng)頭的值,字符串格式;如果沒有請求頭,返回 nil
  • 用法:
-- Given a response with the following headers:
-- X-Custom-Header: bla
-- X-Another: foo bar
-- X-Another: baz

kong.log.inspect(kong.service.response.get_header("x-custom-header")) -- "bla"
kong.log.inspect(kong.service.response.get_header("X-Another"))       -- "foo bar"

kong.table

Lua table 工具類

kong.table.new([narr[, nrec]])

返回一個 table,其中包含了預(yù)先分配的數(shù)組和散列

  • 參數(shù):
    narr(number, optional):指定在數(shù)組組件中預(yù)分布的插槽數(shù)
    nrec(number, optional):指定在散列組件中預(yù)分布的插槽數(shù)
  • 返回值:
    新創(chuàng)建的 table,table 格式
  • 用法:
local  tab  =  kong.table.new(4,  4)

kong.table.clear(tab)

清理 table

  • 參數(shù):
    tab(table):需要被清理的 table
  • 返回值:
  • 用法:
local tab = {
  "hello",
  foo = "bar"
}

kong.table.clear(tab)

kong.log(tab[1]) -- nil
kong.log(tab.foo) -- nil
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容