util_http.lua 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. sys.taskInit(
  21. function()
  22. log.debug("util_http.fetch", "开始请求", "id:", id)
  23. res_code, res_headers, res_body = http.request(method, url, headers, body, opts).wait()
  24. log.debug("util_http.fetch", "请求结束", "id:", id, "code:", res_code)
  25. sys.publish(id)
  26. end
  27. )
  28. local result = sys.waitUntil(id, timeout + 1000 * 25)
  29. if not result or res_code == -8 then
  30. log.warn("util_http.fetch", "请求超时", "id:", id)
  31. end
  32. http_running_count = http_running_count - 1
  33. if http_running_count == 0 then
  34. util_netled.blink()
  35. end
  36. return res_code, res_headers, res_body
  37. end
  38. return util_http