詳細(xì)的開(kāi)發(fā)文檔:https://docs.konghq.com/2.0.x/plugin-development/
一、背景
今天我們來(lái)快速開(kāi)發(fā)一個(gè)kong插件账蓉,插件的功能是客戶(hù)端可以傳遞一個(gè)lambda函數(shù),在Kong網(wǎng)關(guān)中運(yùn)行工三,運(yùn)行結(jié)果會(huì)以Header頭的形式返回到客戶(hù)端架谎。
大家可以通過(guò)這個(gè)插件,來(lái)快速的體驗(yàn)PDK提供的函數(shù)接口。
二君纫、安裝Kong
CentOS系統(tǒng)可以使用下面的命令來(lái)完成安裝
sudo yum install -y wget
wget https://bintray.com/kong/kong-rpm/rpm -O bintray-kong-kong-rpm.repo
export major_version=`grep -oE '[0-9]+\.[0-9]+' /etc/redhat-release | cut -d "." -f1`
sed -i -e 's/baseurl.*/&\/centos\/'$major_version''/ bintray-kong-kong-rpm.repo
sudo mv bintray-kong-kong-rpm.repo /etc/yum.repos.d/
sudo yum install -y kong
三 啟動(dòng)Kong
- 創(chuàng)建配置文件
cp /etc/kong/kong.conf.default /etc/kong/kong.conf
- 修改配置文件
/etc/kong/kong.conf
sed -i "/^#database/i\database = off" /etc/kong/kong.conf
- 啟動(dòng)kong
kong start
- 查看默認(rèn)配置
如果訪問(wèn)成功驯遇,代表kong已經(jīng)成功運(yùn)行
curl http://127.0.0.1:8001/config
四、開(kāi)發(fā)插件
- 進(jìn)入到kong的插件目錄
/usr/local/share/lua/5.1/kong/plugins
蓄髓,創(chuàng)建兩個(gè)lua文件
cd /usr/local/share/lua/5.1/kong/plugins
mkdir debug
cd debug
cat > schema.lua <<EOF
local typedefs = require "kong.db.schema.typedefs"
return {
name = "debug",
fields = {
{ protocols = typedefs.protocols_http },
{ config = {
type = "record",
fields = {
{ lambda_name = { type = "string", default = "X-Kong-Lambda" }, },
{ result_name = { type = "string", default = "X-Kong-Result" }, },
},
},
},
},
}
EOF
cat > handler.lua <<EOF
local cjson = require("cjson.safe").new()
local DebugHandler = {}
DebugHandler.PRIORITY = 6
DebugHandler.VERSION = "2.0.0"
function DebugHandler:header_filter(conf)
local lambda = kong.request.get_header(conf.lambda_name)
if lambda then
local result = cjson.encode(loadstring(lambda)())
kong.response.set_header(conf.result_name, result)
end
end
EOF
cd
- 自動(dòng)加載插件叉庐,修改配置文件
/etc/kong/kong.conf
sed -i "/^#plugins/i\plugins = bundled,debug" /etc/kong/kong.conf
- 重新啟動(dòng)kong
kong restart
- 修改apis.yaml,配置插件
cd
cat > apis.yml <<EOF
_format_version: "1.1"
services:
- name: httpbin-service
url: http://httpbin.org/
# Entities can store tags as metadata
tags:
- httpbin
# Entities that have a foreign-key relationship can be nested:
routes:
- name: httpbin-route
paths:
- /
plugins:
- name: debug
config:
lambda_name: X-Kong-Lambda
result_name: X-Kong-Result
EOF
- 檢測(cè)配置文件是否合法
kong config parse apis.yml
- 上傳配置文件
curl http://127.0.0.1:8001/config -F "config=@apis.yml"
- 測(cè)試接口
# curl -v \
-H "X-Kong-Lambda: return kong.router.get_service().name" \
http://127.0.0.1:8000/ip