nixos-config/nix/verify/modules/http.nix
2024-09-16 08:53:03 +07:00

94 lines
2.6 KiB
Nix

{
lib,
config,
pkgs,
...
}:
with lib;
with types;
{
options.verify.http = mkOption {
default = { };
example = {
github = {
url = "https://github.com";
expectedContent = "GitHub";
};
};
description = ''
Run curl commands to verify if response code is as expected and expectedContent is part of the body.
'';
type = attrsOf (submodule {
options = {
url = mkOption {
type = str;
description = ''
URL to analyze.
'';
};
responseCode = mkOption {
type = int;
default = 200;
description = ''
Expected response code
'';
};
expectedContent = mkOption {
type = nullOr str;
description = ''
Expected string in the response
'';
};
};
});
};
config = {
verify.localCommands =
let
curl = lib.getExe pkgs.curl;
grep = lib.getExe pkgs.gnugrep;
scriptWithExpectedContent = url: responseCode: expectedContent: ''
if ${curl} -s -o /dev/null -w "%{http_code}" ${url} | ${grep} -q "${toString responseCode}"; then
if ${curl} -s ${url} | ${grep} -q "${expectedContent}"; then
echo -n ""
#echo " [ OK ] Die Seite hat Statuscode ${toString responseCode} und enthält den String '${expectedContent}'."
else
echo " [Fail] Der Statuscode ist 200, aber die Seite enthält den String '${expectedContent}' nicht."
fi
else
echo " [Fail] Die Seite hat keinen Statuscode ${toString responseCode}."
fi
'';
scriptWithoutExpectedContent = url: responseCode: ''
if ${curl} -s -o /dev/null -w "%{http_code}" ${url} | ${grep} -q "${toString responseCode}"; then
echo -n ""
#echo " [ OK ] Die Seite hat Statuscode ${toString responseCode}."
else
echo " [Fail] Die Seite hat keinen Statuscode ${toString responseCode}."
fi
'';
script =
url: responeCode: expectedContent:
if (expectedContent == null) then
scriptWithExpectedContent url responeCode expectedContent
else
scriptWithoutExpectedContent url responeCode;
in
mapAttrs' (
service:
{
url,
responseCode,
expectedContent,
}:
nameValuePair ("http_" + service) (script url responseCode expectedContent)
) config.verify.http;
};
}