util_http.lua 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. local util_http = {}
  2. -- 用于生成 http 请求的 id
  3. local http_count = 0
  4. -- 记录正在运行的 http 请求数量
  5. local http_running_count = 0
  6. --- 对 http.request 的封装
  7. -- @param timeout 超时时间(单位: 毫秒)
  8. -- @param method 请求方法
  9. -- @param url 请求地址
  10. -- @param headers 请求头
  11. -- @param body 请求体
  12. function util_http.fetch(timeout, method, url, headers, body)
  13. collectgarbage("collect")
  14. timeout = timeout or 1000 * 25
  15. local opts = { timeout = timeout }
  16. http_count = http_count + 1
  17. http_running_count = http_running_count + 1
  18. local id = "http_" .. http_count
  19. local res_code, res_headers, res_body = -99, {}, ""
  20. util_netled.blink(50, 50)
  21. log.debug("util_http.fetch", "开始请求", "id:", id)
  22. res_code, res_headers, res_body = http.request(method, url, headers, body, opts).wait()
  23. log.debug("util_http.fetch", "请求结束", "id:", id, "code:", res_code)
  24. if res_code == -8 then log.warn("util_http.fetch", "请求超时", "id:", id) end
  25. http_running_count = http_running_count - 1
  26. if http_running_count == 0 then util_netled.blink() end
  27. collectgarbage("collect")
  28. return res_code, res_headers, res_body
  29. end
  30. return util_http