Module jls.net.http.handler.RestHttpHandler

Provide a simple REST HTTP handler based on a Lua table.

Class RestHttpHandler

restHttpHandler:initialize (handlers[, attributes[, noBody]]) Creates a REST HttpHandler.


Class RestHttpHandler

A RestHttpHandler class.
restHttpHandler:initialize (handlers[, attributes[, noBody]])
Creates a REST HttpHandler. The handlers consists in a deep table of functions representing the resource paths. By default the request body is processed and JSON value is available with the attribute "requestJson". The function returned value is used for the HTTP response. A table will be returned as a JSON value. The returned value could also be a promise. An empty string is used as table key for the root resource. The special table key "{name}" is used to match any key and provide the value in the attribue "name".

Parameters:

  • handlers table the REST path handlers as a Lua table.
  • attributes table exchange attributes. (optional)
  • noBody boolean true to indicate the body should not be consumed. (optional)

Usage:

    local users = {}
    httpServer:createContext('/(.*)', RestHttpHandler:new({
      users = {
        [''] = function(exchange)
          return users
        end,
        -- additional handler
        ['{+}?method=GET'] = function(exchange, userId)
          exchange:setAttribute('user', users[userId])
        end,
        ['{userId}'] = {
          ['(user)?method=GET'] = function(exchange, user)
            return user
          end,
          ['(userId, requestJson)?method=POST,PUT'] = function(exchange, userId, requestJson)
            users[userId] = requestJson
          end,
          -- will be available at /rest/users/{userId}/greetings
          ['greetings(user)?method=GET'] = function(exchange, user)
            return 'Hello '..user.firstname
          end
        },
      }
    }))
generated by LDoc 1.4.6 Last updated 2022-01-22 16:32:56