Module jls.net.http.HttpServer

An HTTP server implementation that handles HTTP requests.

Class HttpServer

HttpServer:new () Creates a new HTTP server.
httpServer:createContext (path, handler) Creates a context in this server with the specified path and using the specified handler.
httpServer:addContexts (contexts) Adds the specified contexts.
httpServer:bind ([node[, port[, backlog[, callback]]]]) Binds this server to the specified address and port number.
httpServer:close ([callback]) Closes this server.


Class HttpServer

An HTTP server. The basic HTTP 1.1 server implementation.

Usage:

local event = require('jls.lang.event')
local HttpServer = require('jls.net.http.HttpServer')
local hostname, port = '::', 3001
local httpServer = HttpServer:new()
httpServer:bind(hostname, port):next(function()
  print('Server bound to "'..hostname..'" on port '..tostring(port))
end, function(err) -- could failed if address is in use or hostname cannot be resolved
  print('Cannot bind HTTP server, '..tostring(err))
end)
httpServer:createContext('/', function(httpExchange)
  local response = httpExchange:getResponse()
  response:setBody('It works !')
end)
event:loop()
HttpServer:new ()
Creates a new HTTP server.

Returns:

    a new HTTP server
httpServer:createContext (path, handler)
Creates a context in this server with the specified path and using the specified handler. The path is a Lua pattern that match the full path, take care of escaping the magic characters ^$()%.[]*+-?. You could use the jls.util.strings.escape() function. The path is absolute and starts with a slash '/'.

Parameters:

  • path string The path of the context.
  • handler The handler or a handler function. The function takes one argument which is the HttpExchange and will be called when the body is available.

Returns:

    the new context
httpServer:addContexts (contexts)
Adds the specified contexts. It could be a mix of contexts or pair of path, handler to create.

Parameters:

  • contexts table The contexts to add.

Returns:

    the new context
httpServer:bind ([node[, port[, backlog[, callback]]]])
Binds this server to the specified address and port number.

Parameters:

  • node string the address, the address could be an IP address or a host name. (optional)
  • port number the port number, 0 to let the system automatically choose a port, default is 80. (optional)
  • backlog number the accept queue size, default is 32. (optional)
  • callback function an optional callback function to use in place of promise. (optional)

Returns:

    jls.lang.Promise a promise that resolves once the server is bound.

Usage:

    local s = HttpServer:new()
    s:bind('127.0.0.1', 80)
httpServer:close ([callback])
Closes this server.

Parameters:

  • callback function an optional callback function to use in place of promise. (optional)

Returns:

    jls.lang.Promise a promise that resolves once the server is closed.
generated by LDoc 1.4.6 Last updated 2022-04-10 21:20:13