httpserver-header.lua 1.5 KB

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