server.lua 2.1 KB

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