kong.tools.utils

Module containing some general utility functions used in many places in Kong.

NOTE: Before implementing a function here, consider if it will be used in many places across Kong. If not, a local function in the appropriate module is preferred.

Info:

Functions

add_error (errors, k, v) Add an error message to a key/value table.
check_hostname (address) parses and validates a hostname.
check_https (allow_terminated) Checks whether a request is https or was originally https (but already terminated).
concat (...) Concatenates lists into a new table.
deep_copy (orig) Deep copies a table into a new table.
encode_args (args, raw) Encode a Lua table to a querystring Tries to mimic ngx_lua's ngx.encode_args, but also percent-encode querystring values.
format_host (p1, p2) Formats an ip address or hostname with an (optional) port for use in urls.
get_hostname () Retrieves the hostname of the local machine
hostname_type (name) checks the hostname type; ipv4, ipv6, or name.
is_array (t) Checks if a table is an array and not an associative array.
load_module_if_exists (module_name) Try to load a module.
normalize_ip (address) verifies and normalizes ip addresses and hostnames.
normalize_ipv4 (address) parses, validates and normalizes an ipv4 address.
normalize_ipv6 (address) parses, validates and normalizes an ipv6 address.
pack (...) packs a set of arguments in a table.
random_string () Generates a random unique string
shallow_copy (orig) Copies a table into a new table.
split () splits a string.
strip () strips whitespace from a string.
table_contains (arr, val) Checks if a value exists in a table.
table_merge (t1, t2) Merges two table together.
unpack (t, i, j) unpacks a table to a list of arguments.
uuid () Generates a v4 uuid.
validate_header_name (name) Validates a header name.

Functions


add_error

Add an error message to a key/value table. If the key already exists, a sub table is created with the original and the new value.
Parameters:
  • errors (Optional) Table to attach the error to. If nil, the table will be created.
  • k Key on which to insert the error in the errors table.
  • v Value of the error
Returns:
  • The errors table with the new error inserted.

check_hostname

parses and validates a hostname.
Parameters:
  • address the string containing the hostname (formats; name, name:port)
Returns:
  • hostname (string) + port (number or nil), or alternatively nil+error

check_https

Checks whether a request is https or was originally https (but already terminated). It will check in the current request (global ngx table). If the header X-Forwarded-Proto exists with value https then it will also be considered as an https connection.
Parameters:
  • allow_terminated if truthy, the X-Forwarded-Proto header will be checked as well.
Returns:
  • boolean or nil+error in case the header exists multiple times

concat

Concatenates lists into a new table.
Parameters:
  • ...

deep_copy

Deep copies a table into a new table. Tables used as keys are also deep copied, as are metatables
Parameters:
  • orig The table to copy
Returns:
  • Returns a copy of the input table

encode_args

Encode a Lua table to a querystring Tries to mimic ngx_lua's ngx.encode_args, but also percent-encode querystring values. Supports multi-value query args, boolean values. It also supports encoding for bodies (only because it is used in http_client for specs.
Parameters:
  • args table A key/value table containing the query args to encode.
  • raw boolean If true, will not percent-encode any key/value and will ignore special boolean rules.
Returns:
  • string A valid querystring (without the prefixing '?')
See also:

format_host

Formats an ip address or hostname with an (optional) port for use in urls. Supports ipv4, ipv6 and names.

Explicitly accepts 'nil+error' as input, to pass through any errors from the normalizing and name checking functions.

Parameters:
  • p1 address to format, either string with name/ip, table returned from normalize_ip, or from the socket.url library.
  • p2 port (optional) if p1 is a table, then this port will be inserted if no port-field is in the table
Returns:
  • formatted address or nil+error
Usage:
  • local addr, err = format_ip(normalize_ip("001.002.003.004:123"))  --> "1.2.3.4:123"
    local addr, err = format_ip(normalize_ip("::1"))                  --> "[0000:0000:0000:0000:0000:0000:0000:0001]"
    local addr, err = format_ip("::1", 80))                           --> "[::1]:80"
    local addr, err = format_ip(check_hostname("//bad..name\\"))      --> nil, "invalid hostname: ..."

get_hostname

Retrieves the hostname of the local machine
Returns:
  • string The hostname

hostname_type

checks the hostname type; ipv4, ipv6, or name. Type is determined by exclusion, not by validation. So if it returns 'ipv6' then it can only be an ipv6, but it is not necessarily a valid ipv6 address.
Parameters:
  • name the string to check (this may contain a portnumber)
Returns:
  • string either; 'ipv4', 'ipv6', or 'name'
Usage:
  • hostname_type("123.123.123.123")  -->  "ipv4"
    hostname_type("::1")              -->  "ipv6"
    hostname_type("some::thing")      -->  "ipv6", but invalid...

is_array

Checks if a table is an array and not an associative array. * NOTE * string-keys containing integers are considered valid array entries!
Parameters:
  • t The table to check
Returns:
  • Returns true if the table is an array, false otherwise

load_module_if_exists

Try to load a module. Will not throw an error if the module was not found, but will throw an error if the loading failed for another reason (eg: syntax error).
Parameters:
  • module_name Path of the module to load (ex: kong.plugins.keyauth.api).
Returns:
  • success A boolean indicating whether the module was found.
  • module The retrieved module, or the error in case of a failure

normalize_ip

verifies and normalizes ip addresses and hostnames. Supports ipv4, ipv4:port, ipv6, [ipv6]:port, name, name:port. Returned ipv4 addresses will have no leading zero's, ipv6 will be fully expanded without brackets. Note: a name will not be normalized!
Parameters:
  • address string containing the address
Returns:
  • table with the following fields: host (string; normalized address, or name), type (string; 'ipv4', 'ipv6', 'name'), and port (number or nil), or alternatively nil+error on invalid input

normalize_ipv4

parses, validates and normalizes an ipv4 address.
Parameters:
  • address the string containing the address (formats; ipv4, ipv4:port)
Returns:
  • normalized address (string) + port (number or nil), or alternatively nil+error

normalize_ipv6

parses, validates and normalizes an ipv6 address.
Parameters:
  • address the string containing the address (formats; ipv6, [ipv6], [ipv6]:port)
Returns:
  • normalized expanded address (string) + port (number or nil), or alternatively nil+error

pack

packs a set of arguments in a table. Explicitly sets field n to the number of arguments, so it is nil safe
Parameters:
  • ...

random_string

Generates a random unique string
Returns:
  • string The random string (a uuid without hyphens)

shallow_copy

Copies a table into a new table. neither sub tables nor metatables will be copied.
Parameters:
  • orig The table to copy
Returns:
  • Returns a copy of the input table

split

splits a string. just a placeholder to the penlight pl.stringx.split function

strip

strips whitespace from a string. just a placeholder to the penlight pl.stringx.strip function

table_contains

Checks if a value exists in a table.
Parameters:
  • arr The table to use
  • val The value to check
Returns:
  • Returns true if the table contains the value, false otherwise

table_merge

Merges two table together. A new table is created with a non-recursive copy of the provided tables
Parameters:
  • t1 The first table
  • t2 The second table
Returns:
  • The (new) merged table

unpack

unpacks a table to a list of arguments. Explicitly honors the n field if given in the table, so it is nil safe
Parameters:
  • t
  • i
  • j

uuid

Generates a v4 uuid.
Returns:
  • string with uuid

validate_header_name

Validates a header name. Checks characters used in a header name to be valid, as per nginx only a-z, A-Z, 0-9 and '-' are allowed.
Parameters:
  • name (string) the header name to verify
Returns:
  • the valid header name, or nil+error