# 使用 Lua 创建自定义插件

APISIX 的主要功能之一是其通过 [插件](https://docs.apiseven.com/apisix/key-concepts/plugins.md) 的可扩展性。除了各种现有插件外，APISIX 还允许你构建自定义插件以添加额外功能并使用自定义流程管理 API 流量。通常，你使用 [Lua](https://www.lua.org/) 编程语言来实现新插件。APISIX 分 [阶段](https://github.com/openresty/lua-nginx-module/blob/master/README.markdown#directives) 处理请求，相关的插件逻辑在请求路由期间的每个阶段执行。

本指南将引导你完成为 APISIX 开发一个新的自定义 Lua 插件的示例过程。

## 前置条件[​](#前置条件 "前置条件的直接链接")

* 安装 [Docker](https://docs.docker.com/get-docker/)。
* 安装 [cURL](https://curl.se/) 以向服务发送请求进行验证。
* 按照 [快速入门教程](https://docs.apiseven.com/apisix/getting-started.md) 在 Docker 或 Kubernetes 中启动一个新的 APISIX 实例。
* 如果启用了 [Admin API 身份验证](https://docs.apiseven.com/apisix/production/security/admin-api-key.md)，请将管理员角色的密钥导出为 `ADMIN_API_KEY`。

## 开发文件代理插件[​](#开发文件代理插件 "开发文件代理插件的直接链接")

在本节中，你将使用 Lua 为 APISIX 创建一个名为 **file-proxy** 的新自定义插件。此插件将用于通过 API 公开静态文件（YAML、JSON、JavaScript、CSS 或图像文件）并从指定的 URL 获取文件。 例如，API 用户可以通过指定的 URL `http://127.0.0.1:9080/openapi.yaml` 访问 `openapi.yaml` 文件。

### 创建 Lua 文件[​](#创建-lua-文件 "创建 Lua 文件的直接链接")

为插件源代码创建一个名为 `file-proxy.lua` 的新 Lua 文件。

### 导入模块[​](#导入模块 "导入模块的直接链接")

为 `file-proxy` 插件导入必要的模块：

```
local core = require("apisix.core")

local io = require("io")

local ngx = ngx
```

### 定义插件名称[​](#定义插件名称 "定义插件名称的直接链接")

为插件声明一个唯一的名称：

```
local plugin_name = "file-proxy"
```

### 定义插件架构[​](#定义插件架构 "定义插件架构的直接链接")

为插件参数创建一个架构。架构定义了可用参数及其数据类型、属性、默认值、有效值等。

`file-proxy` 示例仅接受 `/usr/local/apisix/openapi.yaml`，也就是下文创建的公开规范文件。Schema 会拒绝其他字面路径，`access` 处理函数在打开文件前也会再次检查解析后的值。请勿使用教程插件提供凭证或其他私有文件。

```
local allowed_path = "/usr/local/apisix/openapi.yaml"



local plugin_schema = {

    type = "object",

    properties = {

        path = {

            type = "string",

            enum = {allowed_path}

        },

    },

    required = {"path"}

}
```

❶ 要服务的文件的路径。

❷ 路径设置为必需参数。

### 定义 Lua 模块表[​](#定义-lua-模块表 "定义 Lua 模块表的直接链接")

为插件定义属性 `version`、`priority`、`name` 和 `schema`。`name` 和 `schema` 是之前定义的插件名称和架构。`version` 和 `priority` 由 APISIX 用于管理插件。

```
local _M = {

    version = 1.0,

    priority = 1000,

    name = plugin_name,

    schema = plugin_schema

}
```

❶ `version`：该字段通常是指当前正在使用的版本。如果你发布并更新你的插件逻辑，它将是 `1.1`（你可以设置你希望的任何版本）。

❷ `priority`：该字段用于在执行插件的每个阶段之前对插件进行排序。具有较高优先级的插件首先执行。确保自定义插件的优先级适合现有插件的优先级。现有插件的优先级记录在 [`config.yaml.example`](https://github.com/apache/apisix/blob/3.20.0/conf/config.yaml.example#L542) 文件中。

❸ `name`：插件的名称。

❹ `schema`：插件的架构。

### 定义架构检查函数[​](#定义架构检查函数 "定义架构检查函数的直接链接")

定义一个架构检查器以根据定义的架构验证用户输入的参数：

```
function _M.check_schema(conf)

  local ok, err = core.schema.check(plugin_schema, conf)

  if not ok then

      return false, err

  end

  return true

end
```

### 定义自定义逻辑[​](#定义自定义逻辑 "定义自定义逻辑的直接链接")

APISIX 允许你在各种 [阶段](https://docs.apiseven.com/apisix/key-concepts/plugins.md#%E6%8F%92%E4%BB%B6%E6%89%A7%E8%A1%8C%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F) 中注入自定义逻辑。请参阅 [Lua NGINX 模块指令](https://openresty-reference.readthedocs.io/en/latest/Directives/) 以了解有关不同阶段的更多信息。

在 `access` 函数中实现 `file-proxy` 插件的自定义逻辑，该函数将在 access 阶段执行。逻辑应该打开插件配置中指定的文件，读取其内容，并将内容作为响应返回。如果文件无法打开，它应该记录错误并返回 `404 Not Found`。

```
function _M.access(conf, ctx)

  if conf.path ~= allowed_path then

    core.log.error("File path is not allowed")

    return ngx.HTTP_FORBIDDEN

  end



  local fd, err = io.open(conf.path, "rb")

  if not fd then

    core.log.error("File is not found: ", conf.path, ", error info: ", err)

    return ngx.HTTP_NOT_FOUND

  end



  local content = fd:read("*all")

  fd:close()

  ngx.header.content_length = #content

  return ngx.HTTP_OK, content

end
```

### 定义日志逻辑[​](#定义日志逻辑 "定义日志逻辑的直接链接")

`log` 函数在 log 阶段执行。日志记录是可选的，但有助于调试和检查插件是否正常工作。

仅记录该示例中已受约束的配置。不要转储请求上下文，因为其中可能包含凭证和其他私有请求数据：

```
function _M.log(conf, ctx)

    core.log.warn("conf: ", core.json.encode(conf))

end
```

### 组合所有内容[​](#组合所有内容 "组合所有内容的直接链接")

当你组合上面的所有代码时，`file-proxy.lua` 应该如下所示：

```
-- Introduce the necessary modules/libraries we need for this plugin

local core     = require("apisix.core")

local io       = require("io")

local ngx      = ngx



-- Declare the plugin's name

local plugin_name = "file-proxy"

local allowed_path = "/usr/local/apisix/openapi.yaml"



-- Define the plugin schema format

local plugin_schema = {

    type = "object",

    properties = {

        path = {

            type = "string", -- The path of the file to be served

            enum = {allowed_path}

        },

    },

    required = {"path"} -- The path is a required field

}



-- Define the plugin with its version, priority, name, and schema

local _M = {

    version = 1.0,

    priority = 1000,

    name = plugin_name,

    schema = plugin_schema

}



-- Function to check if the plugin configuration is correct

function _M.check_schema(conf)

  -- Validate the configuration against the schema

  local ok, err = core.schema.check(plugin_schema, conf)

  -- If validation fails, return false and the error

  if not ok then

      return false, err

  end

  -- If validation succeeds, return true

  return true

end



-- Function to be called during the access phase

function _M.access(conf, ctx)

  -- Check the resolved value before opening the file.

  if conf.path ~= allowed_path then

    core.log.error("File path is not allowed")

    return ngx.HTTP_FORBIDDEN

  end



  -- Open the file specified in the configuration

  local fd, err = io.open(conf.path, "rb")

  -- If the file cannot be opened, log an error and return a 404 Not Found status

  if not fd then

    core.log.error("File is not found: ", conf.path, ", error info: ", err)

    return ngx.HTTP_NOT_FOUND

  end



  -- Read the file and return its content as the response

  local content = fd:read("*all")

  fd:close()

  ngx.header.content_length = #content

  return ngx.HTTP_OK, content

end





-- Function to be called during the log phase

function _M.log(conf, ctx)

    -- Log the constrained plugin configuration

    core.log.warn("conf: ", core.json.encode(conf))

end



-- Return the plugin so it can be used by APISIX

return _M
```

## 加载自定义插件[​](#加载自定义插件 "加载自��定义插件的直接链接")

有两种方法可以将自定义插件代码加载到 APISIX 中：

1. 将插件源代码放在默认的 APISIX 插件目录 `/apisix/plugins` 中，与其他 APISIX 插件放在一起。
2. 将插件源代码放在单独的目录中，并在 `config.yaml` 中的 `extra_lua_path` 中指定搜索路径。

以下部分提供了第二种方法的说明，因为建议在单独的目录中管理自定义代码。

### Create Custom Plugin File

APISIX 在你的自定义目录中的 `/apisix/plugins` 中查找 L7 插件，在 `/apisix/stream/plugins` 中查找 L4 插件。

对于自定义插件，创建一个具有自定义名称的目录，并在该目录中创建 `/apisix/plugins`：

```
docker exec apisix-quickstart /bin/sh -c "mkdir -p custom-plugin/apisix/plugins"
```

将插件文件保存到该目录：

```
docker exec apisix-quickstart /bin/sh -c "echo '

local core     = require(\"apisix.core\")

local io       = require(\"io\")

local ngx      = ngx



local plugin_name = \"file-proxy\"

local allowed_path = \"/usr/local/apisix/openapi.yaml\"



local plugin_schema = {

    type = \"object\",

    properties = {

        path = {

            type = \"string\",

            enum = {allowed_path}

        },

    },

    required = {\"path\"}

}



local _M = {

    version = 1.0,

    priority = 1000,

    name = plugin_name,

    schema = plugin_schema

}



function _M.check_schema(conf)

  local ok, err = core.schema.check(plugin_schema, conf)

  if not ok then

      return false, err

  end

  return true

end



function _M.access(conf, ctx)

  if conf.path ~= allowed_path then

    core.log.error(\"File path is not allowed\")

    return ngx.HTTP_FORBIDDEN

  end



  local fd, err = io.open(conf.path, \"rb\")

  if not fd then

    core.log.error(\"File is not found: \", conf.path, \", error info: \", err)

    return ngx.HTTP_NOT_FOUND

  end



  local content = fd:read(\"*all\")

  fd:close()

  ngx.header.content_length = #content

  return ngx.HTTP_OK, content

end



function _M.log(conf, ctx)

    core.log.warn(\"conf: \", core.json.encode(conf))

end



return _M

' > /usr/local/apisix/custom-plugin/apisix/plugins/file-proxy.lua"
```

### 更新 APISIX 配置文件[​](#更新-apisix-配置文件 "更新 APISIX 配置文件的直接链接")

将完整的当前[配置文件](https://docs.apiseven.com/apisix/reference/configuration-files.md#configyaml-and-configyamlexample)复制到宿主机并保留备份：

```
docker cp apisix-quickstart:/usr/local/apisix/conf/config.yaml ./config.yaml

cp ./config.yaml ./config.yaml.backup
```

在 `config.yaml` 中现有的 `apisix` 映射下设置自定义插件搜索路径：

config.yaml (custom plugin search path)

```
apisix:

  extra_lua_path: "/usr/local/apisix/custom-plugin/?.lua"
```

将 `file-proxy` 追加到完整的现有顶层 `plugins` 列表。如果当前配置文件省略了该列表，请先从此版本的配置示例中复制完整的默认列表，再追加 `file-proxy`。保留其他所有设置，尤其是 Admin API 白名单、身份验证和 etcd 连接设置。

警告

定义顶层 `plugins` 列表会替换默认列表。请勿配置仅包含 `file-proxy` 的单插件列表。

将候选配置复制到容器中并进行测试，仅在验证成功后重新加载 APISIX：

```
docker cp ./config.yaml apisix-quickstart:/usr/local/apisix/conf/config.yaml

docker exec apisix-quickstart apisix test && \

  docker exec apisix-quickstart apisix reload
```

如果验证失败，请先恢复备份，再进行其他更改：

```
docker cp ./config.yaml.backup apisix-quickstart:/usr/local/apisix/conf/config.yaml
```

## 测试自定义插件[​](#测试自定义插件 "测试自定义插件的直接链接")

### 存储测试文件[​](#存储测试文件 "存储测试文件的直接链接")

在 APISIX 实例中存储一个静态 `openapi.yaml` 文件：

```
docker exec apisix-quickstart /bin/sh -c "printf '%s\n' \

  'openapi: 3.0.1' \

  'info:' \

  '  title: OpenAPI Spec' \

  '  description: OpenAPI Spec file description.' \

  > /usr/local/apisix/openapi.yaml"
```

### 创建路由[​](#创建路由 "创建路由的直接链接")

要使用 `file-proxy` 自定义插件，你需要在 APISIX 中创建一个使用该插件的路由：

* Admin API
* ADC

```
curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

  "id":"openapi-file-proxy",

  "uri":"/openapi.yaml",

  "plugins":{

     "file-proxy":{

        "path":"/usr/local/apisix/openapi.yaml"

     }

  }

}'
```

adc.yaml

```
services:

  - name: OpenAPI File Proxy Service

    labels:

      docs-example: custom-lua-plugin

    routes:

      - uris:

          - /openapi.yaml

        name: openapi-file-proxy

        plugins:

          file-proxy:

            path: /usr/local/apisix/openapi.yaml
```

ADC 将服务协调为期望状态。仅预览本示例带标签的服务，并确认差异中没有非预期的更新或删除：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=custom-lua-plugin
```

同步已审查的服务配置：

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=custom-lua-plugin
```

### 验证插件[​](#验证插件 "验证插件的直接链接")

向路由发送请求：

```
curl -i "http://127.0.0.1:9080/openapi.yaml"
```

响应的 `Content-Length` 应为 `89` 字节，正文应与 `openapi.yaml` 完全一致：

```
HTTP/1.1 200 OK

Content-Length: 89

...



openapi: 3.0.1

info:

  title: OpenAPI Spec

  description: OpenAPI Spec file description.
```

暂时移走文件，以验证错误处理路径：

```
docker exec apisix-quickstart mv \

  /usr/local/apisix/openapi.yaml \

  /usr/local/apisix/openapi.yaml.bak



curl -i "http://127.0.0.1:9080/openapi.yaml"
```

请求应返回 `HTTP/1.1 404 Not Found`。在恢复文件之前，检查错误日志最近 100 行中该插件的消息：

```
docker exec apisix-quickstart /bin/sh -c \

  'tail -n 100 /usr/local/apisix/logs/error.log | \

  grep -F "File is not found" | tail -n 1'
```

输出应包含所配置的路径和操作系统错误，类似于：

```
File is not found: /usr/local/apisix/openapi.yaml, error info: /usr/local/apisix/openapi.yaml: No such file or directory
```

检查响应和日志后恢复文件：

```
docker exec apisix-quickstart mv \

  /usr/local/apisix/openapi.yaml.bak \

  /usr/local/apisix/openapi.yaml
```

## 下一步[​](#下一步 "下一步的直接链接")

使用 Lua 开发自定义插件是扩展 APISIX 的一种方式。接下来，你可以：

* 如需在不重新部署或重启 APISIX 的情况下检查插件运行时状态，请参阅[设置断点](https://docs.apiseven.com/apisix/troubleshooting/set-breakpoints.md)。
* 如需使用 Lua 之外的语言编写插件，请参阅[创建 WASM 插件](https://docs.apiseven.com/apisix/how-to-guide/custom-plugins/wasm-plugins.md)。APISIX 还支持通过外部插件运行器执行 Go、Java 和 Python 插件。
