Skip to content

Instantly share code, notes, and snippets.

@StartAutomating
Last active April 9, 2025 22:42
Show Gist options
  • Save StartAutomating/fb229d462f2b8bbeda67220c2b5740d5 to your computer and use it in GitHub Desktop.
Save StartAutomating/fb229d462f2b8bbeda67220c2b5740d5 to your computer and use it in GitHub Desktop.
Gist a small event-based HTTP server in PowerShell
$JobName = "http://localhost:$(Get-Random -Min 4200 -Max 42000)/"
$httpListener = [Net.HttpListener]::new()
$httpListener.Prefixes.Add($JobName)
$httpListener.Start()
Start-ThreadJob -ScriptBlock {
param($MainRunspace, $httpListener, $SourceIdentifier = 'http')
while ($httpListener.IsListening) {
$contextAsync = $httpListener.GetContextAsync()
while (-not ($contextAsync.IsCompleted -or $contextAsync.IsFaulted -or $contextAsync.IsCanceled)) {}
if ($contextAsync.IsFaulted) {
Write-Error -Exception $contextAsync.Exception -Category ProtocolError
continue
}
$context = $(try { $contextAsync.Result } catch { $_ })
$url = $context.Request.Url
if ($url -match '/favicon.ico$') {
$context.Response.StatusCode = 404
$context.Response.Close()
continue
}
$MainRunspace.Events.GenerateEvent(
$SourceIdentifier, $httpListener, @($context, $context.Request, $context.Response),
[Ordered]@{Url = $context.Request.Url;Context = $context;Request = $context.Request;Response = $context.Response}
)
}
} -Name $JobName -ArgumentList ([Runspace]::DefaultRunspace, $httpListener) -ThrottleLimit 50 |
Add-Member -NotePropertyMembers ([Ordered]@{HttpListener = $httpListener}) -PassThru
Write-Host "Now Serving $jobName" -ForegroundColor Green
$rng = [Random]::new()
while ($httpListener.IsListening) {
foreach ($event in @(Get-Event HTTP*)) {
$context, $request, $response = $event.SourceArgs
if (-not $response.OutputStream) { continue }
$response.Close($outputEncoding.GetBytes("$($rng.Next())"), $false)
Write-Host "Responded to $($request.Url) in $([DateTime]::Now - $event.TimeGenerated)" -ForegroundColor Cyan
$event | Remove-Event
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment