course_query.lua 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. -- =========================================
  2. -- json查询接口
  3. -- =========================================
  4. -- 仅允许 GET 请求
  5. if ngx.req.get_method() ~= "GET" then
  6. ngx.status = ngx.HTTP_NOT_ALLOWED
  7. ngx.header["Content-Type"] = "application/json"
  8. ngx.say('{"error":"Method not allowed, only GET is supported."}')
  9. return ngx.exit(ngx.HTTP_NOT_ALLOWED)
  10. end
  11. local cjson = require "cjson.safe"
  12. ngx.header.content_type = "application/json; charset=utf-8"
  13. -- 获取请求路径
  14. local uri = ngx.var.uri
  15. -- 多个前缀匹配
  16. local prefixes = {
  17. "/api/json/",
  18. "/api/device/json/"
  19. }
  20. local matched_prefix = nil
  21. for _, prefix in ipairs(prefixes) do
  22. if uri:find(prefix) == 1 then
  23. matched_prefix = prefix
  24. break
  25. end
  26. end
  27. if not matched_prefix then
  28. ngx.status = 404
  29. ngx.say(cjson.encode({ code = 404, msg = "未找到匹配的前缀: " .. uri }))
  30. return
  31. end
  32. local relative_path = uri:sub(#matched_prefix + 1)
  33. -- 默认 all.json
  34. if relative_path == "" then
  35. relative_path = "all.json"
  36. elseif not relative_path:match("%.json$") then
  37. relative_path = relative_path .. ".json"
  38. end
  39. local filepath = "/opt/course/json/" .. relative_path
  40. -- 打开文件
  41. local file, err = io.open(filepath, "r")
  42. if not file then
  43. ngx.status = 404
  44. ngx.say(cjson.encode({ code = 404, msg = "未找到字典文件: " .. relative_path }))
  45. return
  46. end
  47. -- 读取文件内容
  48. local content = file:read("*a")
  49. file:close()
  50. -- 校验 JSON 格式
  51. local json_data = cjson.decode(content)
  52. if not json_data then
  53. ngx.status = 500
  54. ngx.say(cjson.encode({ code = 500, msg = "JSON 格式错误: " .. relative_path }))
  55. return
  56. end
  57. -- 组装响应
  58. local result = cjson.encode({code = 200, msg = "success", data = json_data})
  59. ngx.say(result)