Skip to content

Commit bd71b4f

Browse files
committed
Schema validation: update HTTP sample
1 parent 6691a7c commit bd71b4f

File tree

1 file changed

+29
-6
lines changed
  • doc/code_snippets/snippets/config/instances.enabled/application_role_http_api

1 file changed

+29
-6
lines changed

doc/code_snippets/snippets/config/instances.enabled/application_role_http_api/http-api.lua

Lines changed: 29 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,37 @@
11
-- http-api.lua --
22
local httpd
33
local json = require('json')
4+
local schema = require('experimental.config.utils.schema')
45

5-
local function validate(cfg)
6-
if cfg.host then
7-
assert(type(cfg.host) == "string", "'host' should be a string containing a valid IP address")
6+
local function validate_host(host, w)
7+
local host_pattern = "^(%d+)%.(%d+)%.(%d+)%.(%d+)$"
8+
if not host:match(host_pattern) then
9+
w.error("'host' should be a string containing a valid IP address, got %q", host)
10+
end
11+
end
12+
13+
local function validate_port(port, w)
14+
if port <= 1 or port >= 65535 then
15+
w.error("'port' should be between 1 and 65535, got %d", port)
816
end
9-
if cfg.port then
10-
assert(type(cfg.port) == "number", "'port' should be a number")
11-
assert(cfg.port >= 1 and cfg.port <= 65535, "'port' should be between 1 and 65535")
17+
end
18+
19+
local listen_address_schema = schema.new('listen_address', schema.record({
20+
host = schema.scalar({
21+
type = 'string',
22+
validate = validate_host,
23+
}),
24+
port = schema.scalar({
25+
type = 'integer',
26+
validate = validate_port,
27+
}),
28+
}))
29+
30+
local function validate(cfg)
31+
if cfg.host and cfg.port then
32+
listen_address_schema:validate(cfg)
33+
else
34+
error("You need to set both host and port values")
1235
end
1336
end
1437

0 commit comments

Comments
 (0)