course_query.lua 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. -- =========================================
  2. -- json查询接口
  3. -- =========================================
  4. local cjson = require "cjson.safe"
  5. ngx.header.content_type = "application/json; charset=utf-8"
  6. -- 获取请求路径
  7. local uri = ngx.var.uri
  8. local prefix = "/api/json/"
  9. local relative_path = uri:sub(#prefix + 1)
  10. -- 默认 all.json
  11. if relative_path == "" then
  12. relative_path = "all.json"
  13. elseif not relative_path:match("%.json$") then
  14. relative_path = relative_path .. ".json"
  15. end
  16. local filepath = "/opt/server_json/" .. relative_path
  17. -- 打开文件
  18. local file, err = io.open(filepath, "r")
  19. if not file then
  20. ngx.status = 404
  21. ngx.say(cjson.encode({ code = 404, msg = "未找到字典文件: " .. relative_path }))
  22. return
  23. end
  24. -- 读取文件内容
  25. local content = file:read("*a")
  26. file:close()
  27. -- 校验 JSON 格式
  28. local json_data = cjson.decode(content)
  29. if not json_data then
  30. ngx.status = 500
  31. ngx.say(cjson.encode({ code = 500, msg = "JSON 格式错误: " .. relative_path }))
  32. return
  33. end
  34. -- 组装响应
  35. local result = cjson.encode({code = 200, msg = "success", data = json_data})
  36. ngx.say(result)