| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970 |
- -- =========================================
- -- json查询接口
- -- =========================================
- -- 仅允许 GET 请求
- if ngx.req.get_method() ~= "GET" then
- ngx.status = ngx.HTTP_NOT_ALLOWED
- ngx.header["Content-Type"] = "application/json"
- ngx.say('{"error":"Method not allowed, only GET is supported."}')
- return ngx.exit(ngx.HTTP_NOT_ALLOWED)
- end
- local cjson = require "cjson.safe"
- ngx.header.content_type = "application/json; charset=utf-8"
- -- 获取请求路径
- local uri = ngx.var.uri
- -- 多个前缀匹配
- local prefixes = {
- "/api/json/",
- "/api/device/json/"
- }
- local matched_prefix = nil
- for _, prefix in ipairs(prefixes) do
- if uri:find(prefix) == 1 then
- matched_prefix = prefix
- break
- end
- end
- if not matched_prefix then
- ngx.status = 404
- ngx.say(cjson.encode({ code = 404, msg = "未找到匹配的前缀: " .. uri }))
- return
- end
- local relative_path = uri:sub(#matched_prefix + 1)
- -- 默认 all.json
- if relative_path == "" then
- relative_path = "all.json"
- elseif not relative_path:match("%.json$") then
- relative_path = relative_path .. ".json"
- end
- local filepath = "/opt/course/json/" .. relative_path
- -- 打开文件
- local file, err = io.open(filepath, "r")
- if not file then
- ngx.status = 404
- ngx.say(cjson.encode({ code = 404, msg = "未找到字典文件: " .. relative_path }))
- return
- end
- -- 读取文件内容
- local content = file:read("*a")
- file:close()
- -- 校验 JSON 格式
- local json_data = cjson.decode(content)
- if not json_data then
- ngx.status = 500
- ngx.say(cjson.encode({ code = 500, msg = "JSON 格式错误: " .. relative_path }))
- return
- end
- -- 组装响应
- local result = cjson.encode({code = 200, msg = "success", data = json_data})
- ngx.say(result)
|