-
Notifications
You must be signed in to change notification settings - Fork 2
/
file-proxy.lua
67 lines (59 loc) · 1.89 KB
/
file-proxy.lua
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
-- 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"
-- Define the plugin schema format
local plugin_schema = {
type = "object",
properties = {
path = {
type = "string" -- The path of the file to be served
},
},
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)
-- Open the file specified in the configuration
local fd = io.open(conf.path, "rb")
-- If the file is opened successfully, read its content and return it as the response
if fd then
local content = fd:read("*all")
fd:close()
ngx.header.content_length = #content
ngx.say(content)
ngx.exit(ngx.OK)
else
-- If the file cannot be opened, log an error and return a 404 Not Found status
ngx.exit(ngx.HTTP_NOT_FOUND)
core.log.error("File is not found: ", conf.path, ", error info: ", err)
end
end
-- Function to be called during the log phase
function _M.log(conf, ctx)
-- Log the plugin configuration and the request context
core.log.warn("conf: ", core.json.encode(conf))
core.log.warn("ctx: ", core.json.encode(ctx, true))
end
-- Return the plugin so it can be used by APISIX
return _M