devops intermediate
How to create a simple HTTP health check endpoint
Question
How do I create a lightweight HTTP server in Perl for health check endpoints?
Use HTTP::Daemon to create a simple health check server:
#!/usr/bin/perl
use strict;
use warnings;
use HTTP::Daemon;
use HTTP::Status;
my $port = 8080;
my $daemon = HTTP::Daemon->new(
LocalPort => $port,
ReuseAddr => 1,
) or die "Cannot start server: $!";
print "Health check server running on port $port\n";
while (my $client = $daemon->accept) {
while (my $request = $client->get_request) {
if ($request->method eq 'GET' && $request->uri->path eq '/health') {
# Perform health checks
my $status = check_system_health();
if ($status->{healthy}) {
$client->send_response(HTTP::Response->new(
200, 'OK', ['Content-Type' => 'text/plain'],
"Status: healthy\nUptime: $status->{uptime}\n"
));
} else {
$client->send_response(HTTP::Response->new(
503, 'Service Unavailable', ['Content-Type' => 'text/plain'],
"Status: unhealthy\nReason: $status->{reason}\n"
));
}
} else {
$client->send_error(404);
}
}
$client->close;
}
sub check_system_health {
# Add your health check logic here
return { healthy => 1, uptime => `uptime` };
}
This script creates a simple HTTP server with a /health endpoint that returns 200 OK when healthy or 503 when problems are detected.