Skip to content

Instantly share code, notes, and snippets.

@leobm
Created May 5, 2026 14:01
Show Gist options
  • Select an option

  • Save leobm/3b09fda35b769156816cff52176ae234 to your computer and use it in GitHub Desktop.

Select an option

Save leobm/3b09fda35b769156816cff52176ae234 to your computer and use it in GitHub Desktop.
Here's perhaps a slightly more comprehensive interface of how it could be built
use strict;
use warnings FATAL => 'all';
# The Request object ($req)
# - method(): Returns GET, POST, etc.
#
# - path(): The path itself (e.g., /user/profile).
#
# - query($key): Extracts values from the query string after the ?.
#
# - header($name): Returns the value of a specific HTTP header.
#
# - cookie($name): Parses the cookie header and returns the value.
#
# - body(): Automatically detects the content type (JSON/Form) and returns a hash reference.
#
#=======================================================================================================
# The Response object ($res)
# - status($code): Sets the HTTP status code (200, 404, etc.). Enables “chaining” ($res->status(200)->send(...)).
#
# - header($key, $val): Adds a header to the response.
#
# - cookie($name, $val, \%options): Creates a valid Set-Cookie header.
#
# - json($data): Automatically sets the Content-Type to application/json and serializes the data.
#
# - send($code, $content): The final method that puts everything together and closes the socket.
my $server = HttpServer->new();
# example Middleware
$server->use(sub {
my ($req, $res) = @_;
print "Eingehender Request: " . $req->method . " " . $req->path . "\n";
});
# Eine komplexe Route
$server->get('/user/profile', sub {
my ($req, $res) = @_;
# 1. read Query-Params (?id=123&mode=dark)
my $user_id = $req->query('id');
my $theme = $req->query('mode') // 'light';
# 2. read header
my $auth_token = $req->header('Authorization');
# 3. read Cookies
my $session_id = $req->cookie('session_id');
if (!$auth_token) {
# 4. Fehlerantwort mit Custom Header
return $res->status(401)
->header('WWW-Authenticate', 'Bearer')
->json({ error => 'Nicht autorisiert' });
}
# 5. set Cookie and send Response
$res->status(200)
->cookie('last_visit', time(), { expires => 3600, httponly => 1 })
->header('X-Powered-By', 'MyPerlServer')
->json({
id => $user_id,
theme => $theme,
state => 'active'
});
});
# POST-Example (file)
$server->post('/upload', sub {
my ($req, $res) = @_;
my $data = $req->body(); # Parsed JSON oder Form-Data
my $file = $req->file('image'); # Zugriff auf hochgeladene Dateien
$res->send(201, "Datei empfangen!");
});
$server->start(port => 8080);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment