| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647 |
- -- =========================================
- -- json查询接口
- -- =========================================
- local cjson = require "cjson.safe"
- ngx.header.content_type = "application/json; charset=utf-8"
- -- 获取请求路径
- local uri = ngx.var.uri
- local prefix = "/api/json/"
- local relative_path = uri:sub(#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/server_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)
|