http.liq 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # Set of HTTP utils.
  2. %include "http_codes.liq"
  3. # Create a HTTP response string
  4. # @category Interaction
  5. # @param ~protocol HTTP protocol used.
  6. # @param ~code Response code.
  7. # @param ~headers Response headers.
  8. # @param ~data Response data
  9. def http_response(~protocol="HTTP/1.1",
  10. ~code=200,
  11. ~headers=[],
  12. ~data="") =
  13. status = http_codes[string_of(code)]
  14. # Set content-length and connection: close
  15. headers =
  16. list.append(headers,
  17. [("Content-Length", "#{string.length(data)}"),
  18. ("Connection", "close")])
  19. headers = list.map(fun (x) -> "#{fst(x)}: #{snd(x)}",headers)
  20. headers = string.concat(separator="\r\n",headers)
  21. # If no headers are provided, we should avoid
  22. # having an empty line for them. Therefore, we also
  23. # conditionally add the final \r\n here.
  24. headers =
  25. if headers != "" then
  26. "#{headers}\r\n"
  27. else
  28. headers
  29. end
  30. "#{protocol} #{code} #{status}\r\n\
  31. #{headers}\
  32. \r\n\
  33. #{data}"
  34. end