httpserver-header.lua 1.5 KB

12345678910111213141516171819202122232425262728293031323334
  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)
  5. local function getHTTPStatusString(code)
  6. local codez = {[200]="OK", [400]="Bad Request", [404]="Not Found", [501]="Not Implemented",}
  7. local myResult = codez[code]
  8. if myResult then return myResult else return "Unknown HTTP Status" end
  9. end
  10. local function getMimeType(ext)
  11. local gzip = false
  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", jpg = "image/jpeg", js = "application/javascript", json = "application/json", png = "image/png", xml = "text/xml"}
  14. -- add comressed flag if file ends with gz
  15. if ext:find("%.gz$") then
  16. ext = ext:sub(1, -4)
  17. gzip = true
  18. end
  19. if mt[ext] then contentType = mt[ext] else contentType = "text/plain" end
  20. return {contentType = contentType, gzip = gzip}
  21. end
  22. local mimeType = getMimeType(extension)
  23. connection:send("HTTP/1.0 " .. code .. " " .. getHTTPStatusString(code) .. "\r\nServer: nodemcu-httpserver\r\nContent-Type: " .. mimeType["contentType"] .. "\r\n")
  24. if mimeType["gzip"] then
  25. connection:send("Content-Encoding: gzip\r\n")
  26. end
  27. connection:send("Connection: close\r\n\r\n")
  28. end