Http
Tarantool http server
Install / Use
/learn @tarantool/HttpREADME
HTTP server for Tarantool 1.7.5+
Note: In Tarantool 1.7.5+, a full-featured HTTP client is available aboard. For Tarantool 1.6.5+, both HTTP server and client are available here.
http v2 has gone
http v2 that was implemented in
#90 has been reverted in a
master branch (commits
01004d7..e7e00ea)
and a limited number of reverted commits were reimplemented on top of http v1.
However http v2 changes are still available in a branch
http-v2-legacy as well as Lua
rockspecs available with name http-v2-legacy instead of http. For reasons of
http v2 revert and decisions regarding each reverted commit see
#134.
Table of contents
- Prerequisites
- Installation
- Usage
- Creating a server
- Using routes
- Contents of app_dir
- Route handlers
- Working with stashes
- Working with cookies
- Rendering a template
- Template helpers
- Hooks
- Using a special socket
- Roles
- See also
Prerequisites
- Tarantool 1.7.5+ with header files (
tarantool&&tarantool-devpackages)
Installation
You can:
-
clone the repository and build the
httpmodule using CMake:git clone https://github.com/tarantool/http.git cd http && cmake . -DCMAKE_BUILD_TYPE=RelWithDebugInfo make make install -
install the
httpmodule using tt:tt rocks install http -
install the
httpmodule using LuaRocks (see TarantoolRocks for LuaRocks configuration details):luarocks --server=https://rocks.tarantool.org/ --local install http
Usage
The server is an object which is configured with HTTP request handlers, routes (paths), templates, and a port to bind to. Unless Tarantool is running under a superuser, port numbers below 1024 may be unavailable.
The server can be started and stopped anytime. Multiple servers can be created.
To start a server:
- Create it with
httpd = require('http.server').new(...). - Configure routing with
httpd:route(...). - Start it with
httpd:start().
To stop the server, use httpd:stop().
Creating a server
httpd = require('http.server').new(host, port[, { options } ])
host and port must contain:
- For tcp socket: the host and port to bind to.
- For unix socket:
unix/and path to socket (for example/tmp/http-server.sock) to bind to.
options may contain:
-
max_header_size(default is 4096 bytes) - a limit for HTTP request header size. -
header_timeout(default: 100 seconds) - a timeout until the server stops reading HTTP headers sent by the client. The server closes the client connection if the client doesn't send its headers within the given amount of time. -
app_dir(default is '.', the server working directory) - a path to the directory with HTML templates and controllers. -
handler- a Lua function to handle HTTP requests (this is a handler to use if the module "routing" functionality is not needed). -
charset- the character set for server responses of typetext/html,text/plainandapplication/json. -
display_errors- return application errors and backtraces to the client (like PHP). Disabled by default (since 1.2.0). -
log_requests- log incoming requests. This parameter can receive:- function value, supporting C-style formatting: log_requests(fmt, ...), where fmt is a format string and ... is Lua Varargs, holding arguments to be replaced in fmt.
- boolean value, where
truechoose defaultlog.infoandfalsedisable request logs at all.
By default uses
log.infofunction for requests logging. -
log_errors- same as thelog_requestsoption but is used for error messages logging. By default useslog.error()function. -
disable_keepalive- disables keep-alive connections with misbehaving clients. Parameter accept a table that contains a user agents names. By default table is empty.Example:
local httpd = http_server.new('127.0.0.1', 8080, { log_requests = true, log_errors = true, disable_keepalive = { 'curl/7.68.0' } }) -
idle_timeout- maximum amount of time an idle (keep-alive) connection will remain idle before closing. When the idle timeout is exceeded, HTTP server closes the keepalive connection. Default value: 0 seconds (disabled). -
TLS options (to enable it, provide at least one of the following parameters):
ssl_cert_fileis a path to the SSL cert file, mandatory;ssl_key_fileis a path to the SSL key file, mandatory;ssl_ca_fileis a path to the SSL CA file, optional;ssl_ciphersis a colon-separated list of SSL ciphers, optional;ssl_passwordis a password for decrypting SSL private key, optional;ssl_password_fileis a SSL file with key for decrypting SSL private key, optional.ssl_verify_clientis an option that allows to verify client. It has following values:off(default) means that no client's certs will be verified;onmeans that server will verify client's certs;optionalmeans that server will verify client's certs only if it exist.
Using routes
It is possible to automatically route requests between different handlers, depending on the request path. The routing API is inspired by Mojolicious API.
Routes can be defined using:
- an exact match (e.g. "index.php")
- simple regular expressions
- extended regular expressions
Route examples:
'/' -- a simple route
'/abc' -- a simple route
'/abc/:cde' -- a route using a simple regular expression
'/abc/:cde/:def' -- a route using a simple regular expression
'/ghi*path' -- a route using an extended regular expression
To configure a route, use the route() method of the httpd object:
httpd:route({ path = '/path/to' }, 'controller#action')
httpd:route({ path = '/', template = 'Hello <%= var %>' }, handle1)
httpd:route({ path = '/:abc/cde', file = 'users.html.el' }, handle2)
httpd:route({ path = '/objects', method = 'GET' }, handle3)
...
To delete a named route, use delete() method of the httpd object:
httpd:route({ path = '/path/to', name = 'route' }, 'controller#action')
httpd:delete('route')
The first argument for route() is a Lua table with one or more keys:
file- a template file name (can be relative to.{app_dir}/templates, whereapp_diris the path set when creating the server). If no template file name extension is provided, the extension is set to ".html.el", meaning HTML with embedded Lua.template- template Lua variable name, in case the template is a Lua variable. Iftemplateis a function, it's called on every request to get template body. This is useful if template body must be taken from a database.path- route path, as described earlier.name- route name.method- method on the route likePOST,GET,PUT,DELETElog_requests- option that overrides the server parameter of the same name but only for current route.log_errors- option that overrides the server parameter of the same name but only for current route.
The second argument is the route handler to be used to produce a response to the request.
The typical usage is to avoid passing file and template arguments,
since they take time to evaluate, but these arguments are useful
for writing tests or defining HTTP servers with just one "route".
The handler can also be passed as a string of the form 'filename#functionname'.
In that case, the handler body is taken from a file in the
{app_dir}/controllers directory.
Contents of app_dir
public- a path to static content. Everything stored on this path defines a route which matches the file name, and the HTTP server serves this file automatically, as is. Notice that the server doesn't usesendfile(), and it reads the entire content of the file into the memory before passing it to the client. ??? Caching is not used, unless turned on. So this is not suitable for large files, use nginx instead.templates- a path to templates.controllers- a path to *.lua files with Lua controllers. For example, the controller name 'module.submodule#foo' is mapped to `{app_dir}/con
Related Skills
node-connect
341.2kDiagnose OpenClaw node connection and pairing failures for Android, iOS, and macOS companion apps
frontend-design
84.5kCreate distinctive, production-grade frontend interfaces with high design quality. Use this skill when the user asks to build web components, pages, or applications. Generates creative, polished code that avoids generic AI aesthetics.
openai-whisper-api
341.2kTranscribe audio via OpenAI Audio Transcriptions API (Whisper).
commit-push-pr
84.5kCommit, push, and open a PR
