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. timeout = timeout or 1000 * 25
  14. local opts = {timeout = timeout}
  15. http_count = http_count + 1
  16. http_running_count = http_running_count + 1
  17. local id = "http_" .. http_count
  18. local res_code, res_headers, res_body = -99, {}, ""
  19. util_netled.blink(50, 50)
  20. log.debug("util_http.fetch", "开始请求", "id:", id)
  21. res_code, res_headers, res_body = http.request(method, url, headers, body, opts).wait()
  22. log.debug("util_http.fetch", "请求结束", "id:", id, "code:", res_code)
  23. if res_code == -8 then
  24. log.warn("util_http.fetch", "请求超时", "id:", id)
  25. end
  26. http_running_count = http_running_count - 1
  27. if http_running_count == 0 then
  28. util_netled.blink()
  29. end
  30. return res_code, res_headers, res_body
  31. end
  32. return util_http