Resource Web Access: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
m (Add new-feature-item wrapper for router)
 
(24 intermediate revisions by 17 users not shown)
Line 1: Line 1:
The Multi Theft Auto Server provides a web interface that resources can use in a variety of ways. This document's purpose is to explain what these ways are and how to go about using them.
The Multi Theft Auto Server provides a web interface that resources can use in a variety of ways. This document's purpose is to explain what these ways are and how to go about using them.
{{Note|If you are looking for a tutorial on how to use the in-game web browser and create websites using CEF, please visit [[CEF_Tutorial|CEF Tutorial]] instead.}}


==Visión de conjunto==
Hay dos partes principales que componen este sistema. El primero es un servidor web estándar que permite a los navegadores de Internet para solicitar páginas y archivos que tienes en un recurso. El segundo es un sistema para permitir que los navegadores de Internet para llamar a las funciones que ha exportado de su recurso.


==Paginas==
==Overview==
===Espesificación de un archivo meta===
There are three key parts that make up this system.
Tu puedes especificar en su archivo de datos meta de recursos de que ciertos archivos sean accesibles a través del servidor web. Para eso, puedes agregar estas lineas:
* '''Pages:''' The ability to serve any http items (specified the meta.xml) as a page or file.
<syntaxhighlight lang="lua" lang="xml">
* '''Calls:''' The ability to call any exported http functions (specified in the meta.xml).
{{New feature/item|3.0161|1.6.0|22639|* '''Router:''' Use a designated http function to route requests within a resource manually (overriding the two parts above).}}
 
==Pages==
===Specifying a file in the meta===
You can specify in your resource's meta file that certain files are accessible through the web server. To do this, you add a line:
<syntaxhighlight lang="xml">
<html src="filename.ext" />
<html src="filename.ext" />
</syntaxhighlight>
</syntaxhighlight>
Tambien puedes acceder a este archivo de navegador web en: http://host:port/resourcename/filename.ext<br/>
You can then access this file from your web browser by visiting: http://host:port/resourcename/filename.ext<br/>
Por ejemplo, en un servidor alojado localmente utilizando el puerto HTTP predeterminado con webmap comenzó: http://127.0.0.1:22005/webmap/map.htm
For example, on a locally hosted server using default http port with webmap started: http://127.0.0.1:22005/webmap/map.htm
 


===Archivos Binarios===


A pesar del nombre engañoso, los archivos especificados mediante el nodo html pueden ser de cualquier tipo. Si son archivos binarios (como imágenes, archivos zip), entonces usted tiene que especificar esto en el archivo meta, mediante la adición de crudo'' = "true"'' al nodo'' html''. Esto significa que los archivos no se preprocesa antes de ser enviado al navegador web.
===Binary files===
Despite the misleading name, files specified using the html node can be of any type. If they are binary files (like images, zip files) then you need to specify this in the meta file, by adding ''raw="true"'' to the ''html'' node. This means that the files are not preprocessed before being sent to the web browser.


Por ejemplo:
For example:
<syntaxhighlight lang="lua" lang="xml">
<syntaxhighlight lang="xml">
<html src="image.gif" raw="true" />
<html src="image.gif" raw="true" />
</syntaxhighlight>
</syntaxhighlight>


===Analizada archivos===
===Parsed files===
Si un archivo no se ha especificado en el archivo de metadatos como "cruda", entonces se pasa a través de un pre-procesador antes de que se devuelve al cliente. Este procesador pre-funciona como PHP o ASP, pero utiliza LUA. Puede incrustar secuencias de comandos estándar del MTA dentro de las páginas HTML, el control de la salida. Casi todos los estándares de trabajo MTA funciones, además de un número especial de [[Plantilla: Funciones | Funciones HTTP HTTP]], como [[httpWrite]], una función que envía texto al buffer.
If a file is not specified in the metafile as "raw", then it is passed through a pre-processor before it is returned to the client. This pre-processor works much like PHP or ASP but uses Lua. You can embed standard MTA scripts within HTML pages, controlling the output. Almost all standard MTA functions work, plus a number of special [[Template:HTTP functions|HTTP Functions]], such as [[httpWrite]], a function that outputs text to the buffer.


Por ejemplo:
For example:
<syntaxhighlight lang="lua" lang="html">
<syntaxhighlight lang="html4strict">
<html>
<html>
     <body>
     <body>
         Este recurso se llama <* httpWrite( getResourceName(getThisResource()) ) *>
         This resource is called <* httpWrite( getResourceName(getThisResource()) ) *>
     </body>
     </body>
<html>
<html>
</syntaxhighlight>
</syntaxhighlight>


Hay un atajo (en común con PHP y ASP) para este código, lo que significa que también se puede escribir el código anterior como:
There is a shorthand (in common with PHP and ASP) for this code, meaning that you can also write the above code as:


<syntaxhighlight lang="lua" lang="html">
<syntaxhighlight lang="html4strict">
<html>
<html>
     <body>
     <body>
         Este recurso se llama <* = getResourceName(getThisResource()) *>
         This resource is called <* = getResourceName(getThisResource()) *>
     </body>
     </body>
<html>
<html>
</syntaxhighlight>
</syntaxhighlight>


Aparte de las funciones HTTP, integrado Lua tiene acceso a las siguientes variables de entorno que contienen información acerca de cómo la página se solicita:
Aside from HTTP functions, embedded Lua has access to the following environment variables that contain information about how the page was requested:
* Mesa'' 'requestHeaders''': Esta es una tabla que contiene todas las cabeceras que se solicitaron a la página. Puede configurar las cabeceras devueltas mediante [[httpSetResponseHeader]].
* table '''requestHeaders''': This is a table containing all the headers that were requested with the page. You can set returned headers using [[httpSetResponseHeader]].  
* Tabla'' 'form''': Esta es una tabla que contiene todos los datos del formulario presentado a la página utilizando HTTP POST combinar con cualquier variables pasadas en la cadena de consulta con HTTP GET.
* table '''form''': This is a table containing all the form data submitted to the page using HTTP POST combined with any variables passed in the querystring with HTTP GET.
* Tabla'' 'cookies''': Esta es una tabla de todas las cookies. Puede modificar las cookies usando [[httpSetResponseCookie]].
* table '''cookies''': This is a table of all the cookies. You can modify cookies using [[httpSetResponseCookie]].
* Cadena'' 'hostname''': Esta es una cadena que contiene la dirección IP o el nombre de host que solicita la página.
* string '''hostname''': This is a string containing the IP address or hostname that requested the page.
* Cadena'' 'url''': Esta es la URL de la página.
* string '''url''': This is the URL of the page.
Cuenta *'' 'user''': Esta es la cuenta de usuario actual.
* account '''user''': This is the account of the current user.
{{New feature/item|3.0159|1.5.8|20828|
* string '''requestBody''': This is the request body.
* string '''method''': This is the request method.
}}


Es importante tener en cuenta que los archivos analizados se ejecutan en una máquina virtual independiente del resto del código de su recurso. Por lo tanto, si desea llamar a una función en el código de su principal recurso, es necesario exportar la función y el uso de la [[llamada]] función de su archivo analizado.
It's important to note that parsed files are run in a separate virtual machine from the rest of your resource's code. As such, if you want to call a function in your resource's main code, you need to export the function and use the [[call]] function from your parsed file.


==Calls==
==Calls==
Line 59: Line 67:


To specify an exported http-accessible function, add the following to your meta.xml file:
To specify an exported http-accessible function, add the following to your meta.xml file:
<syntaxhighlight lang="lua" lang="xml">
<syntaxhighlight lang="xml">
<export function='functionName' http='true' />
<export function='functionName' http='true' />
</syntaxhighlight>
</syntaxhighlight>


You can code your function just as you would any normal function, returning as many values as you want, including tables and resources and most importantly elements. You ''cannot'' however return other 'userdata' values such as [[xmlnode|xmlnodes]] or functions.
You can code your function just as you would any normal function, returning as many values as you want, including tables and resources and most important elements. You ''cannot'' however return other 'userdata' values such as [[xmlnode|xmlnodes]] or functions.


===Protocolo===
===Protocol===
{{note_box | Usted no necesita saber esto a menos que usted está escribiendo su propio código de solicitud HTTP. Usted sólo puede utilizar uno de los [[# SDK | SDKs enumeran a continuación.]]}}
{{Note|You don't need to know this unless you're writing your own HTTP request code. You can just use one of the [[#SDK|SDKs listed below]].}}


Las llamadas se realizan mediante la solicitud'' <nowiki> http:// <su IP>: <su <puerto / <resource_name> / llamada / <exported_function_name> </ nowiki>'' utilizando HTTP POST. El cuerpo de la solicitud debe ser una matriz JSON de los argumentos de la función.
Calls are done by requesting ''<nowiki>http://<your IP>:<your port>/<resource_name>/call/<exported_function_name></nowiki>'' using HTTP POST. The body of the request should be a JSON array of the arguments for the function.


La solicitud devolverá una matriz JSON del valor (s) devuelto por la función como la respuesta HTTP.
The request will return a JSON array of the value(s) returned from the function as the HTTP response.


El servidor admite autenticación HTTP Basic y se puede configurar el acceso a través de la ACL y el sistema de cuentas integradas.
The server supports HTTP Basic authentication and you can configure access via the ACL and the built-in accounts system.


===Calls from the HTTP web interface===
===Calls from the HTTP web interface===
Line 78: Line 86:


First, add this to your meta.xml file:
First, add this to your meta.xml file:
<syntaxhighlight lang="lua" lang="xml">
<syntaxhighlight lang="xml">
<include resource="ajax" />
<include resource="ajax" />
</syntaxhighlight>
</syntaxhighlight>


Secondly, add the following to the <head> section of the page you want to call from:
Secondly, add the following to the <head> section of the page you want to call from:
<syntaxhighlight lang="lua" lang="lua">
<syntaxhighlight lang="lua">
<* = exports.ajax:start(getResourceName(getThisResource())) *>
<* = exports.ajax:start(getResourceName(getThisResource())) *>
</syntaxhighlight>
</syntaxhighlight>


Finally, you can create a javascript block in your page and call your functions almost as if they were local. The only difference is that the calls are aysnchronous - you should specify a callback function as the last argument for your call. This is called when the function returns.
Finally, you can create a javascript block on your page and call your functions almost as if they were local. The only difference is that the calls are asynchronous - you should specify a callback function as the last argument for your call. This is called when the function returns.


Here's a simple example.
Here's a simple example.


'''meta.xml'''
'''meta.xml'''
<syntaxhighlight lang="lua" lang="xml">
<syntaxhighlight lang="xml">
<meta>
<meta>
   <include resource="ajax" />
   <include resource="ajax" />
Line 102: Line 110:


'''code.lua'''
'''code.lua'''
<syntaxhighlight lang="lua" lang="lua">
<syntaxhighlight lang="lua">
function showChatMessage ( message )
function showChatMessage ( message )
     outputChatBox ( message )
     outputChatBox ( message )
Line 110: Line 118:


'''page.htm'''
'''page.htm'''
<syntaxhighlight lang="lua" lang="html">
<syntaxhighlight lang="html4strict">
<html>
<html>
     <head>
     <head>
Line 133: Line 141:


You can see (fairly complex) examples of how this can be done in the resources ''resourcebrowser'', ''resourcemanager'' and ''webadmin''.
You can see (fairly complex) examples of how this can be done in the resources ''resourcebrowser'', ''resourcemanager'' and ''webadmin''.
==Router==
{{New feature/item|3.0161|1.6.0|22639|
A router is a function that overrides both the function call mechanism and basic web server functionality, to allow a scripter to personalize the routing and client-response for each resource separately. For example, this allows a scripter to write an '''api''' named resource with a router function, that can serve any sort of information in a RESTy fashion. You may also take this further, and name the resource '''v1''' (or '''v2'''...) for easy API versioning. You can spin up and down the different resources as you wish, and users of your API can continue using an older version this way.
}}
===How to setup a router function===
A router function has to be specified in the meta.xml (see example below). You can name the function however you like, there are no restrictions, as long as the function can be found in the global Lua scope in your scripts. '''Note:''' You can have only one router function.
<syntaxhighlight lang="xml">
<export function="httpRouter" http="true" router="true" />
</syntaxhighlight>
Then you have to specify the function in any Lua script:
<syntaxhighlight lang="lua">
function httpRouter(request)
    return 200 -- see below for a more complex return value
end
</syntaxhighlight>
===Request===
This section describes all the fields, that can be found in the '''request''' table passed to the router function for every call. The descriptions below use the following example URL:
<code>http://127.0.0.1:22005/api/vehicles/123?meow=true</code> ('''api''' is the resource name)
{|  class="prettytable" style="width:100%;text-align:left;"
|-
! Field || Type || Description
|-
| <code>account</code> || [[Account]] || An account that was used for this request (can be a [[isGuestAccount|guest account]]).
|-
| <code>method</code> || [[string]] || One of the following: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, PATCH, *
|-
| <code>path</code> || [[string]] || The requested path within your resource: <code>"/vehicles/123"</code>
|-
| <code>absolute_path</code> || [[string]] || The absolute path from the URL: <code>"/api/vehicles/123?meow=true"</code>
|-
| <code>hostname</code> || [[string]] || The hostname of the web server: <code>"127.0.0.1"</code>
|-
| <code>port</code> || [[integer]] || The client port used by the web server: <code>56758</code> (can be anything, but never 22005)
|-
| <code>body</code> || [[string]] || The body portion of the request sent by the client
|-
| <code>query</code> || [[table]] || A key-value table (with [[string]] keys and values) with the path's query fields (only query)
|-
| <code>formData</code> || [[table]] || A key-value table (with [[string]] keys and values) with the request form data (both query and body fields)
|-
| <code>cookies</code> || [[table]] || A key-value table (with [[string]] keys and values) with the request cookies
|-
| <code>headers</code> || [[table]] || A key-value table (with [[string]] keys and values) with the request headers (like User-Agent)
|}
===Response===
This section describes all the possible variants, that can be returned by the router function. There are three variants in total:
* Return literally nothing: response will use http status code ''200'' and an empty body.
* Return an [[integer]]: response will convert the number to an http status code and use an empty body.
* Return a table: response will be filled with the fields from the table (defaults to http status code ''200'' and empty body, if not overriden by a table field).
====Response table fields====
{|  class="prettytable" style="width:100%;text-align:left;"
|-
! Field || Type || Description
|-
| <code>status</code> || [[integer]] || A number that will be converted to an http status code.
|-
| <code>body</code> || [[string]] || A string that will be used for the response body.
|-
| <code>headers</code> || [[table]] || A key-value table (with [[string]] keys and values) that will be written to the header section of the response.
|-
| <code>cookies</code> || [[table]] || A table with simple [[string]] key and value entries, or any-type key with [[table]] values (key is not used), entries. Check the examples below, if it's unclear.
|}
===Examples===
<syntaxhighlight lang="lua">
function httpRouter(request)
    -- HTTP status code 200 & empty body
end
</syntaxhighlight>
<syntaxhighlight lang="lua">
function httpRouter(request)
    return 404 --< HTTP status code & empty body
end
</syntaxhighlight>
<syntaxhighlight lang="lua">
function httpRouter(request)
    return {
        status = 404,
        body = "not found",
    }
end
</syntaxhighlight>
<syntaxhighlight lang="lua">
function httpRouter(request)
    return {
        status = 505,
        body = "foo",
        cookies = {
            foo = "1234",
            {
                name = "bar",  -- Cookie name must always be a lowercase "name" key
                value = "6666",  -- Cookie value must always be a lowercase "value" key
                Version = "2",  -- Any other cookie field can use any case
            }
        },
        headers = {
            ["content-type"] = "text/html",
            ["etag"] = "c561c68d0ba92bbeb8b0f612a9199f722e3a621a",
            ["access-control-allow-origin"] = "*",
            ["x-custom-header"] = "MTA server",
        }
    }
end
</syntaxhighlight>


==Securing the web interface==
==Securing the web interface==
The [[ACL]] has a number of rights that can affect what files can be accessed.
The [[ACL]] has a number of rights that can affect what files can be accessed.
{{Deprecated feature|3.0139|1.3.1|
{{Deprecated feature|3.0139|1.3.1|
* general.http: If disabled, none of the http files can be accessed (except by game clients)
* general.http: If disabled, none of the HTTP files can be accessed (except by game clients)
** '''Important Note''': ''If 'general.http' is enabled, http access to all resources (for that ACL) is enabled by default. To disable http access you have to explicitly block access to resources that contain exported http functions.''
** '''Important Note''': ''If 'general.http' is enabled, HTTP access to all resources (for that ACL) is enabled by default. To disable HTTP access you have to explicitly block access to resources that contain exported HTTP functions.''
** '''Important Note''': ''If 'general.http' is enabled on an ACL which has a user with no password (i.e. user.* or user.guest or user.http_guest), it is essential that you explicitly block access to resources that contain exported http functions.''
** '''Important Note''': ''If 'general.http' is enabled on an ACL which has a user with no password (i.e. user.* or user.guest or user.http_guest), it is essential that you explicitly block access to resources that contain exported HTTP functions.''
* resource.'''ResourceName''': If disabled, none of the files in the resource can be accessed
* resource.'''ResourceName''': If disabled, none of the files in the resource can be accessed
* resource.'''ResourceName'''.file.'''FileName''': If disabled, the file named cannot be accessed
* resource.'''ResourceName'''.file.'''FileName''': If disabled, the file named cannot be accessed
Line 151: Line 275:


==SDK==
==SDK==
There are a number of so-called 'SDKs' available that allow you to interface with the server from other programming languages. With these you could (in theory) write whole gamemodes. In practice this is probably a bad idea, but it is useful for statistics and administration. The PHP SDK is the most developed version. Feel free to modify or create your own SDKs - if you do please send us a copy.
There are a number of so-called 'SDKs' available that allow you to interface with the server from other programming languages. With these, you could (in theory) write whole gamemodes. In practice, this is probably a bad idea, but it is useful for statistics and administration. The PHP SDK is the most developed version. Feel free to modify or create your own SDKs - if you do please send us a copy.


* [[JavaSDK|Java SDK]]
* [[JavaSDK|Java SDK]]
* [[Javascript SDK]]
* [[Javascript SDK]]
* [https://www.npmjs.com/package/mtasa Node.js SDK]
* [https://crates.io/crates/mta-sdk Rust SDK]
* [https://pypi.org/project/MTA-SDK-Python/ Python SDK]
* [[Perl SDK]]
* [[Perl SDK]]
* [[PHP SDK]]
* [[PHP SDK]]
Line 162: Line 289:
[[callRemote]] - Allows game servers to call functions on PHP pages (with the PHP SDK) and on other game servers.
[[callRemote]] - Allows game servers to call functions on PHP pages (with the PHP SDK) and on other game servers.
[[Category:Scripting Concepts]]
[[Category:Scripting Concepts]]
[[en:Resource Web Access]]
[[fr:Ressource Acces Internet]]
[[hu:Resource Web Access]]
[[pt-br:Acesso_web_via_recursos]]
[[ru:Resource Web Access]]
[[ru:Resource Web Access]]
[[Category:Tutorials]]

Latest revision as of 14:32, 25 August 2024

The Multi Theft Auto Server provides a web interface that resources can use in a variety of ways. This document's purpose is to explain what these ways are and how to go about using them.

[[{{{image}}}|link=|]] Note: If you are looking for a tutorial on how to use the in-game web browser and create websites using CEF, please visit CEF Tutorial instead.


Overview

There are three key parts that make up this system.

  • Pages: The ability to serve any http items (specified the meta.xml) as a page or file.
  • Calls: The ability to call any exported http functions (specified in the meta.xml).
ADDED/UPDATED IN VERSION 1.6.0 r22639:
* Router: Use a designated http function to route requests within a resource manually (overriding the two parts above).

Pages

Specifying a file in the meta

You can specify in your resource's meta file that certain files are accessible through the web server. To do this, you add a line:

<html src="filename.ext" />

You can then access this file from your web browser by visiting: http://host:port/resourcename/filename.ext
For example, on a locally hosted server using default http port with webmap started: http://127.0.0.1:22005/webmap/map.htm


Binary files

Despite the misleading name, files specified using the html node can be of any type. If they are binary files (like images, zip files) then you need to specify this in the meta file, by adding raw="true" to the html node. This means that the files are not preprocessed before being sent to the web browser.

For example:

<html src="image.gif" raw="true" />

Parsed files

If a file is not specified in the metafile as "raw", then it is passed through a pre-processor before it is returned to the client. This pre-processor works much like PHP or ASP but uses Lua. You can embed standard MTA scripts within HTML pages, controlling the output. Almost all standard MTA functions work, plus a number of special HTTP Functions, such as httpWrite, a function that outputs text to the buffer.

For example:

<html>
    <body>
        This resource is called <* httpWrite( getResourceName(getThisResource()) ) *>
    </body>
<html>

There is a shorthand (in common with PHP and ASP) for this code, meaning that you can also write the above code as:

<html>
    <body>
        This resource is called <* = getResourceName(getThisResource()) *>
    </body>
<html>

Aside from HTTP functions, embedded Lua has access to the following environment variables that contain information about how the page was requested:

  • table requestHeaders: This is a table containing all the headers that were requested with the page. You can set returned headers using httpSetResponseHeader.
  • table form: This is a table containing all the form data submitted to the page using HTTP POST combined with any variables passed in the querystring with HTTP GET.
  • table cookies: This is a table of all the cookies. You can modify cookies using httpSetResponseCookie.
  • string hostname: This is a string containing the IP address or hostname that requested the page.
  • string url: This is the URL of the page.
  • account user: This is the account of the current user.
  • string requestBody: This is the request body.
  • string method: This is the request method.

It's important to note that parsed files are run in a separate virtual machine from the rest of your resource's code. As such, if you want to call a function in your resource's main code, you need to export the function and use the call function from your parsed file.

Calls

You can specify that certain exported functions in your resource are able to be called from the HTTP interface. All the SDKs (listed below) allow you to call these functions from a remote location.

To specify an exported http-accessible function, add the following to your meta.xml file:

<export function='functionName' http='true' />

You can code your function just as you would any normal function, returning as many values as you want, including tables and resources and most important elements. You cannot however return other 'userdata' values such as xmlnodes or functions.

Protocol

[[{{{image}}}|link=|]] Note: You don't need to know this unless you're writing your own HTTP request code. You can just use one of the SDKs listed below.

Calls are done by requesting http://<your IP>:<your port>/<resource_name>/call/<exported_function_name> using HTTP POST. The body of the request should be a JSON array of the arguments for the function.

The request will return a JSON array of the value(s) returned from the function as the HTTP response.

The server supports HTTP Basic authentication and you can configure access via the ACL and the built-in accounts system.

Calls from the HTTP web interface

Using calls is probably easiest from the web interface and can be done almost seamlessly.

First, add this to your meta.xml file:

<include resource="ajax" />

Secondly, add the following to the <head> section of the page you want to call from:

<* = exports.ajax:start(getResourceName(getThisResource())) *>

Finally, you can create a javascript block on your page and call your functions almost as if they were local. The only difference is that the calls are asynchronous - you should specify a callback function as the last argument for your call. This is called when the function returns.

Here's a simple example.

meta.xml

<meta>
   <include resource="ajax" />
   <script src='code.lua' />
   <html src='page.htm' default='true' />
   <export function='showChatMessage' http='true' />
</meta>

code.lua

function showChatMessage ( message )
    outputChatBox ( message )
    return 5;
end

page.htm

<html>
    <head>
        <* = exports.ajax:start(getResourceName(getThisResource())) *>
        <script type='text/javascript'>
            function say() {
                var message = document.getElementById('message')
                showChatMessage ( message.value, 
                    function ( number ) {
                        // the function has been called and returned something
                        message.value = "The function returned " + number;
                    }
                );
            }
        </script>
    </head>
    <body>
        <input type='text' id='message' /><input type='button' value='say' onclick='say();' />
    </body>
</html>

You can see (fairly complex) examples of how this can be done in the resources resourcebrowser, resourcemanager and webadmin.

Router

ADDED/UPDATED IN VERSION 1.6.0 r22639:

A router is a function that overrides both the function call mechanism and basic web server functionality, to allow a scripter to personalize the routing and client-response for each resource separately. For example, this allows a scripter to write an api named resource with a router function, that can serve any sort of information in a RESTy fashion. You may also take this further, and name the resource v1 (or v2...) for easy API versioning. You can spin up and down the different resources as you wish, and users of your API can continue using an older version this way.

How to setup a router function

A router function has to be specified in the meta.xml (see example below). You can name the function however you like, there are no restrictions, as long as the function can be found in the global Lua scope in your scripts. Note: You can have only one router function.

<export function="httpRouter" http="true" router="true" />

Then you have to specify the function in any Lua script:

function httpRouter(request)
    return 200 -- see below for a more complex return value
end

Request

This section describes all the fields, that can be found in the request table passed to the router function for every call. The descriptions below use the following example URL:

http://127.0.0.1:22005/api/vehicles/123?meow=true (api is the resource name)

Field Type Description
account Account An account that was used for this request (can be a guest account).
method string One of the following: OPTIONS, GET, HEAD, POST, PUT, DELETE, TRACE, CONNECT, PATCH, *
path string The requested path within your resource: "/vehicles/123"
absolute_path string The absolute path from the URL: "/api/vehicles/123?meow=true"
hostname string The hostname of the web server: "127.0.0.1"
port integer The client port used by the web server: 56758 (can be anything, but never 22005)
body string The body portion of the request sent by the client
query table A key-value table (with string keys and values) with the path's query fields (only query)
formData table A key-value table (with string keys and values) with the request form data (both query and body fields)
cookies table A key-value table (with string keys and values) with the request cookies
headers table A key-value table (with string keys and values) with the request headers (like User-Agent)

Response

This section describes all the possible variants, that can be returned by the router function. There are three variants in total:

  • Return literally nothing: response will use http status code 200 and an empty body.
  • Return an integer: response will convert the number to an http status code and use an empty body.
  • Return a table: response will be filled with the fields from the table (defaults to http status code 200 and empty body, if not overriden by a table field).

Response table fields

Field Type Description
status integer A number that will be converted to an http status code.
body string A string that will be used for the response body.
headers table A key-value table (with string keys and values) that will be written to the header section of the response.
cookies table A table with simple string key and value entries, or any-type key with table values (key is not used), entries. Check the examples below, if it's unclear.

Examples

function httpRouter(request)
    -- HTTP status code 200 & empty body
end
function httpRouter(request)
    return 404 --< HTTP status code & empty body
end
function httpRouter(request)
    return {
        status = 404,
        body = "not found",
    }
end
function httpRouter(request)
    return {
        status = 505,
        body = "foo",
        cookies = {
            foo = "1234",
            {
                name = "bar",  -- Cookie name must always be a lowercase "name" key
                value = "6666",  -- Cookie value must always be a lowercase "value" key
                Version = "2",  -- Any other cookie field can use any case
            }
        },
        headers = {
            ["content-type"] = "text/html",
            ["etag"] = "c561c68d0ba92bbeb8b0f612a9199f722e3a621a",
            ["access-control-allow-origin"] = "*",
            ["x-custom-header"] = "MTA server",
        }
    }
end

Securing the web interface

The ACL has a number of rights that can affect what files can be accessed.

This works as with other ACL rights - You can enable it just for Admin users, or any other group of users you wish.

SDK

There are a number of so-called 'SDKs' available that allow you to interface with the server from other programming languages. With these, you could (in theory) write whole gamemodes. In practice, this is probably a bad idea, but it is useful for statistics and administration. The PHP SDK is the most developed version. Feel free to modify or create your own SDKs - if you do please send us a copy.

See Also

callRemote - Allows game servers to call functions on PHP pages (with the PHP SDK) and on other game servers.