支持参数的校验

This commit is contained in:
anlicheng 2025-10-31 11:10:52 +08:00
parent 425981b7e2
commit cea9fff718

View File

@ -180,3 +180,103 @@ handle_request(_, Path, _, _) ->
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%% helper methods %% helper methods
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
validate_config(Config) when is_map(Config) ->
%%
Required = [
{image, binary},
{container_name, binary},
{command, list},
{restart, binary},
{privileged, boolean}
],
%%
Optional = [
{envs, list},
{ports, list},
{expose, list},
{volumes, list},
{networks, list},
{labels, map},
{user, binary},
{working_dir, binary},
{hostname, binary},
{cap_add, list},
{cap_drop, list},
{devices, list},
{mem_limit, binary},
{mem_reservation, binary},
{cpu_shares, integer},
{cpus, number},
{ulimits, map},
{sysctls, map},
{tmpfs, list},
{extra_hosts, list},
{healthcheck, map}
],
Errors1 = check_required(Config, Required),
Errors2 = check_optional(Config, Optional),
Errors = Errors1 ++ Errors2,
case Errors of
[] ->
ok;
_ ->
{error, lists:map(fun erlang:iolist_to_binary/1, Errors)}
end;
validate_config(_) ->
{error, [<<"Config 必须为 map() 类型">>]}.
%%------------------------------------------------------------------------------
%%
%%------------------------------------------------------------------------------
check_required(Config, Fields) ->
lists:foldl(
fun({Key, Type}, ErrAcc) ->
case maps:get(Key, Config, undefined) of
undefined ->
[io_lib:format("缺少必选参数: ~p", [Key]) | ErrAcc];
Value ->
case check_type(Value, Type) of
true ->
ErrAcc;
false ->
[io_lib:format("参数 ~p 类型错误,应为 ~p", [Key, Type]) | ErrAcc]
end
end
end,
[], Fields).
%%------------------------------------------------------------------------------
%%
%%------------------------------------------------------------------------------
check_optional(Config, Fields) ->
lists:foldl(
fun({Key, Type}, ErrAcc) ->
case maps:get(Key, Config, undefined) of
undefined ->
ErrAcc;
Value ->
case check_type(Value, Type) of
true ->
ErrAcc;
false ->
[io_lib:format("可选参数 ~p 类型错误,应为 ~p", [Key, Type]) | ErrAcc]
end
end
end,
[], Fields).
%%------------------------------------------------------------------------------
%% binary版
%%------------------------------------------------------------------------------
check_type(Value, binary) -> is_binary(Value);
check_type(Value, integer) -> is_integer(Value);
check_type(Value, number) -> is_number(Value);
check_type(Value, list) -> is_list(Value);
check_type(Value, map) -> is_map(Value);
check_type(Value, boolean) -> is_boolean(Value);
check_type(_, _) -> false.