httpserver-header.lua 1.5 KB

123456789101112131415161718192021222324252627282930313233343536
  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. if code == 200 then return "OK" end
  7. if code == 404 then return "Not Found" end
  8. if code == 400 then return "Bad Request" end
  9. if code == 501 then return "Not Implemented" end
  10. return "Unknown HTTP status"
  11. end
  12. local function getMimeType(ext)
  13. local gzip = false
  14. -- A few MIME types. Keep list short. If you need something that is missing, let's add it.
  15. 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"}
  16. -- add comressed flag if file ends with gz
  17. if ext:find("%.gz$") then
  18. ext = ext:sub(1, -4)
  19. gzip = true
  20. end
  21. if mt[ext] then contentType = mt[ext] else contentType = "text/plain" end
  22. return {contentType = contentType, gzip = gzip}
  23. end
  24. local mimeType = getMimeType(extension)
  25. connection:send("HTTP/1.0 " .. code .. " " .. getHTTPStatusString(code) .. "\r\nServer: nodemcu-httpserver\r\nContent-Type: " .. mimeType["contentType"] .. "\r\n")
  26. if mimeType["gzip"] then
  27. connection:send("Content-Encoding: gzip\r\n")
  28. end
  29. connection:send("Connection: close\r\n\r\n")
  30. end