-
-
Save PSingletary/228a2aa69e51c607c2810eec9096c1de to your computer and use it in GitHub Desktop.
Gist a small event-based HTTP server in PowerShell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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