server.lua 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. local read = require('read')
  2. local net = net
  3. local string = string
  4. local srv = nil
  5. local debug_message = debug_message
  6. module(...)
  7. local function connect(conn, data)
  8. local query_data
  9. conn:on('receive',
  10. function(cn, req_data)
  11. query_data = get_http_req(req_data)
  12. debug_message(query_data['METHOD'] .. ' ' .. ' ' .. query_data['User-Agent'])
  13. --TODO discriminate endpoints (/, /yo.css, /status, /favicon.ico)
  14. --TODO discriminate request types (POST --> update)
  15. --TODO parse payload function rewrite
  16. send_index(cn)
  17. cn:close()
  18. end
  19. )
  20. end
  21. -- Build and return a table of the http request data
  22. function get_http_req(instr)
  23. local t = {}
  24. local first = nil
  25. local key, v, strt_ndx, end_ndx
  26. for str in string.gmatch(instr, '([^\n]+)') do
  27. -- First line in the method and path
  28. if(first == nil) then
  29. first = 1
  30. strt_ndx, end_ndx = string.find(str, '([^ ]+)')
  31. v = trim(string.sub(str, end_ndx + 2))
  32. key = trim(string.sub(str, strt_ndx, end_ndx))
  33. t['METHOD'] = key
  34. t['REQUEST'] = v
  35. else -- Process and reamaining ':' fields
  36. strt_ndx, end_ndx = string.find(str, '([^:]+)')
  37. if(end_ndx ~= nil) then
  38. v = trim(string.sub(str, end_ndx + 2))
  39. key = trim(string.sub(str, strt_ndx, end_ndx))
  40. t[key] = v
  41. end
  42. end
  43. end
  44. return t
  45. end
  46. -- String trim left and right
  47. function trim(s)
  48. return(s:gsub('^%s*(.-)%s*$', '%1'))
  49. end
  50. function send_index(conn)
  51. debug_message('server.send_index')
  52. index = read.index()
  53. local settings = read.current_settings()
  54. index = string.gsub(index, 'S_', settings.ssid)
  55. index = string.gsub(index, 'T_', settings.status)
  56. index = string.gsub(index, 'R_', settings.yo_to)
  57. debug_message('sending index')
  58. debug_message('____________')
  59. debug_message(index)
  60. debug_message('____________')
  61. conn:send('HTTP/1.1 200 OK\n\n' .. index)
  62. end
  63. function start()
  64. debug_message('server.start')
  65. debug_message(srv)
  66. if srv then
  67. srv = nil
  68. end
  69. srv = net.createServer(net.TCP, 30)
  70. srv:listen(80, connect)
  71. debug_message(srv)
  72. end
  73. function stop()
  74. debug_message('server.stop')
  75. debug_message(srv)
  76. if srv then
  77. srv:close()
  78. srv = nil
  79. end
  80. debug_message(srv)
  81. end