Модуль http | Tarantool
Документация на русском языке
поддерживается сообществом

Модуль http

Модуль http, в частности вложенный модуль http.client , обеспечивает функциональные возможности HTTP-клиента с поддержкой HTTPS и механизмом поддержания в активном состоянии keepalive. Модуль использует процедуры из библиотеки libcurl.

Ниже приведен перечень всех функций модуля http.

Имя Назначение
http.client.new() Создание экземпляра HTTP-клиента
client_object:request() Выполнение HTTP-запроса
client_object:stat() Получение таблицы со статистикой
http.client.new([options])

Создание нового экземпляра HTTP-клиента.

Параметры:
  • options (table) – настройки целочисленных значений, которые передаются в libcurl.

Доступны два параметра: max_connections и max_total_connections.

max_connections – это максимальное количество записей в кэше, которое влияет на CURLMOPT_MAXCONNECTS в libcurl. По умолчанию -1.

max_total_connections is the maximum number of active connections. It affects libcurl CURLMOPT_MAX_TOTAL_CONNECTIONS. It is ignored if the curl version is less than 7.30. The default is 0, which allows libcurl to scale accordingly to easily handles count.

Обычно значений параметров по умолчанию будет достаточно, но в редких случаях может понадобиться их настройка. На этот случай два совета.

  1. You may want to control the maximum number of sockets that a particular HTTP client uses simultaneously. If a system passes many requests to distinct hosts, then libcurl cannot reuse sockets. In this case setting max_total_connections may be useful, since it causes curl to avoid creating too many sockets which would not be used anyway.
  2. Do not set max_connections less than max_total_connections unless you are confident about your actions. When max_connections is less then max_total_connections, in some cases libcurl will not reuse sockets for requests that are going to the same host. If the limit is reached and a new request occurs, then libcurl will first create a new socket, send the request, wait for the first connection to be free, and close it, in order to avoid exceeding the max_connections cache size. In the worst case, libcurl will create a new socket for every request, even if all requests are going to the same host. See this Tarantool issue on Github for details.
возвращает:новый экземпляр HTTP-клиента
тип возвращаемого значения:
 пользовательские данные

Пример:

tarantool> http_client = require('http.client').new({max_connections = 5})
---
...
object client_object
client_object:request(method, url, body, opts)

Если http_client – это экземпляр HTTP-клиента, http_client:request() выполнит HTTP-запрос, и в случае успешного подключения вернет таблицу с информацией о подключении.

Параметры:
  • method (string) – HTTP-метод, например „GET“, „POST“ или „PUT“
  • url (string) – расположение, например „https://tarantool.org/doc
  • body (string) – необязательное начальное сообщение, например „My text string!“
  • opts (table) –

    таблица с параметрами подключения, которые могут содержать любые из следующих компонентов:

    • ca_file – путь к SSL-сертификату для проверки подключенного узла.
    • ca_path – путь к директории, где хранятся один или более сертификатов для проверки подключенного узла.
    • headers – таблица HTTP-заголовков.
    • keepalive_idle – время задержки в секундах, в течение которого операционная система находится в режиме ожидания подключения до отправки сообщений для поддержания в активном состоянии keepalive. См. также CURLOPT_TCP_KEEPIDLE и примечание ниже к keepalive_interval.
    • keepalive_interval – the interval, in seconds, that the operating system will wait between sending keepalive probes. See also CURLOPT_TCP_KEEPINTVL. If both keepalive_idle and keepalive_interval are set, then Tarantool will also set HTTP keepalive headers: Connection:Keep-Alive and Keep-Alive:timeout=<keepalive_idle>. Otherwise, Tarantool will send Connection:close.
    • low_speed_limit – установка «предела низкой скорости» – средней скорости передачи в байтах в секунду, ниже которой должна быть скорость передачи, чтобы библиотека посчитала работу слишком медленной и завершила ее. См. также CURLOPT_LOW_SPEED_LIMIT.
    • low_speed_time – установка «времени работы с низкой скоростью» – времени, в течение которого скорость передачи должна быть ниже «предела низкой скорости», чтобы библиотека посчитала работу слишком медленной и завершила ее. См. также CURLOPT_LOW_SPEED_TIME.
    • max_header_name_len – максимальная длина имени заголовка. Если имя заголовка больше данного значения, оно усекается до такой длины. По умолчанию, 32.
    • follow_location – when the option is set to true (default) and the response has a 3xx code, the HTTP client will automatically issue another request to a location that a server sends in the Location header. If the new response is 3xx again, the HTTP client will issue still another request and so on in a loop until a non-3xx response will be received. This last response will be returned as a result. Setting this option to false allows to disable this behavior. In this case, the HTTP client will return a 3xx response itself.
    • no_proxy – a comma-separated list of hosts that do not require proxies, or „*“, or „“. Set no_proxy = host [, host ...] to specify hosts that can be reached without requiring a proxy, even if proxy has been set to a non-blank value and/or if a proxy-related environment variable has been set. Set no__proxy = '*' to specify that all hosts can be reached without requiring a proxy, which is equivalent to setting proxy=''. Set no_proxy = '' to specify that no hosts can be reached without requiring a proxy, even if a proxy-related environment variable (HTTP_PROXY) is used. If no_proxy is not set, then a proxy-related environment variable (HTTP_PROXY) may be used. See also CURLOPT_NOPROXY.
    • proxy - a proxy server host or IP address, or „“. If proxy is a host or IP address, then it may begin with a scheme, for example https:// for an https proxy or http:// for an http proxy. If proxy is set to „“ – an empty string, then proxy use is disabled, and no proxy-related environment variable will be used. If proxy is not set, then a proxy-related environment variable may be used, such as HTTP_PROXY or HTTPS_PROXY or FTP_PROXY, or ALL_PROXY if the protocol can be any protocol. See also CURLOPT_PROXY.
    • proxy_port – a proxy server port. The default is 443 for an https proxy and 1080 for a non-https proxy. See also CURLOPT_PROXYPORT.
    • proxy_user_pwd – a proxy server user name and/or password. Format: proxy_user_pwd = user_name: or proxy_user_pwd = :password or proxy_user_pwd = user_name:password. See also CURLOPT_USERPWD.
    • ssl_cert – путь к файлу клиентского SSL-сертификата. См. также CURLOPT_SSLCERT.
    • ssl_key – путь к файлу закрытого ключа для клиентского TSL-сертификата и SSL-сертификата. См. также CURLOPT_SSLKEY.
    • timeout – количество секунд ожидания API-запроса curl на чтение до превышения времени ожидания. Значение по умолчанию – бесконечность (36586400100 секунд).
    • unix_socket – имя сокета, которое используется вместо адреса в сети Интернет, для локального соединения. Сборка сервера Tarantool должна осуществляться с помощью libcurl 7.40 или более поздней версии. См. второй пример далее в разделе.
    • verbose – включение/отключение режима отображения подробной информации.
    • verify_host – включение/отключение проверки имени сертификата (CN) для хоста. См. также CURLOPT_SSL_VERIFYHOST.
    • verify_peer – включение/отключение проверки SSL-сертификата подключенного узла. См. также CURLOPT_SSL_VERIFYPEER.
    • accept_encoding – enables automatic decompression of HTTP responses by setting the contents of the Accept-Encoding: header sent in an HTTP request and enabling decoding of a response when the Content-Encoding: header is received. This option specifies what encoding to use. It can be an empty string which means the Accept-Encoding: header will contain all supported built-in encodings. Four encodings are supported: identity, meaning non-compressed, deflate which requests the server to compress its response using the zlib algorithm, gzip which requests the gzip algorithm and br which is brotli. Provide them in the string as a comma-separated list of accepted encodings, like: "br, gzip, deflate". For details of the option, refer to CURLOPT_ACCEPT_ENCODING.
возвращает:

информация о подключении со всеми следующими компонентами:

  • status – статус HTTP-ответа
  • reason – текст статуса HTTP-ответа
  • headers – Lua-таблица с нормализованными HTTP-заголовками
  • body – тело сообщения-ответа
  • proto – версия протокола
тип возвращаемого значения:
 

таблица

Компонент cookies содержит Lua-таблицу, ключом в которой является имя файла cookie. Значением же является массив из двух элементов: первый элемент представляет собой значение данных cookie, а второй – массив с параметрами файла cookie. Возможные параметры: «Expires», «Max-Age», «Domain», «Path», «Secure», «HttpOnly», «SameSite». Обратите внимание, что параметр представляет собой строку, в которой знак „=“ разделяет имя параметра и его значение. Дополнительную информацию можно получить здесь.

Пример:

Информацию по файлам cookies можно использовать следующим образом:

tarantool> require('http.client').get('https://www.tarantool.io/en/').cookies
---
- csrftoken:
  - bWJVkBybvX9LdJ8uLPOTVrit5P3VbRjE3potYVOuUnsSjYT5ahghDV06tXRkfnOl
  - - Max-Age=31449600
    - Path=/
...

tarantool> cookies = require('http.client').get('https://www.tarantool.io/en/').cookies
---
...

tarantool> options = cookies['csrftoken'][2]
---
...

tarantool> for _, option in ipairs(options) do
         > if option:startswith('csrftoken cookie's Max-Age = ') then
         > print(option)
         > end
         > end

csrftoken cookie's Max-Age = 31449600
---
...

tarantool>

Для запросов существуют следующие ускоренные методы:

  • http_client:get(url, options) – вспомогательный метод для http_client:request("GET", url, nil, opts)
  • http_client:post (url, body, options) – ускоренный метод для http_client:request("POST", url, body, opts)
  • http_client:put(url, body, options) – ускоренный метод для http_client:request("PUT", url, body, opts)
  • http_client:patch(url, body, options) – ускоренный метод для http_client:request("PATCH", url, body, opts)
  • http_client:options(url, options) – ускоренный метод для http_client:request("OPTIONS", url, nil, opts)
  • http_client:head(url, options) – ускоренный метод для http_client:request("HEAD", url, nil, opts)
  • http_client:delete(url, options) – ускоренный метод для http_client:request("DELETE", url, nil, opts)
  • http_client:trace(url, options) – ускоренный метод для http_client:request("TRACE", url, nil, opts)
  • http_client:connect(url, options) – ускоренный метод для http_client:request("CONNECT", url, nil, opts)

Requests may be influenced by environment variables, for example users can set up an http proxy by setting HTTP_PROXY=proxy before initiating any requests, unless a proxy connection option has priority. See the web page document Environment variables libcurl understands.

client_object:stat()

Функция http_client:stat() возвращает таблицу со статистическими данными:

  • active_requests – количество активно выполняемых запросов
  • sockets_added – общее количество сокетов, добавленных в событийный цикл
  • sockets_deleted – общее количество сокетов, удаленных из событийного цикла
  • total_requests – общее количество запросов
  • http_200_responses – общее количество запросов, которые вернули код состояния HTTP 200
  • http_other_responses – общее количество запросов, которые не вернули код состояния HTTP 200
  • failed_requests – общее количество невыполненных запросов, включая системные ошибки, ошибки curl и HTTP-ошибки

Пример 1:

Подключение к HTTP-серверу, просмотр размера ответа на „GET“-запрос и просмотр статистики по сессии.

tarantool> http_client = require('http.client').new()
---
...
tarantool> r = http_client:request('GET','http://tarantool.org')
---
...
tarantool> string.len(r.body)
---
- 21725
...
tarantool> http_client:stat()
---
- total_requests: 1
  sockets_deleted: 2
  failed_requests: 0
  active_requests: 0
  http_other_responses: 0
  http_200_responses: 1
  sockets_added: 2

Пример 2:

Запустите два экземпляра Tarantool на одном компьютере.

В первом экземпляре Tarantool включите прослушивание Unix-сокета:

box.cfg{listen='/tmp/unix_domain_socket.sock'}

На втором экземпляре Tarantool отправьте с помощью http_client:

box.cfg{}
http_client = require('http.client').new({5})
http_client:put('http://localhost/','body',{unix_socket = '/tmp/unix_domain_socket.sock'})

Терминал №1 покажет сообщение об ошибке: «Invalid MsgPack». Данный пример бесполезен, но наглядно демонстрирует синтаксис и получение отправленного сообщения.

Нашли ответ на свой вопрос?
Обратная связь