httpserver-header.lua 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. -- httpserver-header.lua
  2. -- Part of nodemcu-httpserver, knows how to send an HTTP header.
  3. -- Author: Marcos Kirsch
  4. return function(connection, code, extension, isGzipped, extraHeaders)
  5. local function getHTTPStatusString(code)
  6. local codez = { [200] = "OK", [400] = "Bad Request", [401] = "Unauthorized", [404] = "Not Found", [405] = "Method Not Allowed", [500] = "Internal Server Error", [501] = "Not Implemented", }
  7. local myResult = codez[code]
  8. -- enforce returning valid http codes all the way throughout?
  9. if myResult then return myResult else return "Not Implemented" end
  10. end
  11. local function getMimeType(ext)
  12. -- A few MIME types. Keep list short. If you need something that is missing, let's add it.
  13. local mt = {css = "text/css", gif = "image/gif", html = "text/html", ico = "image/x-icon", jpeg = "image/jpeg",
  14. jpg = "image/jpeg", js = "application/javascript", json = "application/json", png = "image/png", xml = "text/xml"}
  15. if mt[ext] then return mt[ext] else return "text/plain" end
  16. end
  17. local mimeType = getMimeType(extension)
  18. local statusString = getHTTPStatusString(code)
  19. connection:send("HTTP/1.0 " .. code .. " " .. statusString .. "\r\nServer: nodemcu-httpserver\r\nContent-Type: " .. mimeType .. "\r\n")
  20. if isGzipped then
  21. connection:send("Cache-Control: private, max-age=2592000\r\nContent-Encoding: gzip\r\n")
  22. end
  23. if (extraHeaders) then
  24. for i, extraHeader in ipairs(extraHeaders) do
  25. connection:send(extraHeader .. "\r\n")
  26. end
  27. end
  28. connection:send("Connection: close\r\n\r\n")
  29. return statusString
  30. end