Create a gist now

Instantly share code, notes, and snippets.

A simple web server built with powershell.
function Load-Packages
{
param ([string] $directory = 'Packages')
$assemblies = Get-ChildItem $directory -Recurse -Filter '*.dll' | Select -Expand FullName
foreach ($assembly in $assemblies) { [System.Reflection.Assembly]::LoadFrom($assembly) }
}
Load-Packages
$routes = @{
"/ola" = { return '<html><body>Hello world!</body></html>' }
}
$url = 'http://localhost:8080/'
$listener = New-Object System.Net.HttpListener
$listener.Prefixes.Add($url)
$listener.Start()
Write-Host "Listening at $url..."
while ($listener.IsListening)
{
$context = $listener.GetContext()
$requestUrl = $context.Request.Url
$response = $context.Response
Write-Host ''
Write-Host "> $requestUrl"
$localPath = $requestUrl.LocalPath
$route = $routes.Get_Item($requestUrl.LocalPath)
if ($route -eq $null)
{
$response.StatusCode = 404
}
else
{
$content = & $route
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length)
}
$response.Close()
$responseStatus = $response.StatusCode
Write-Host "< $responseStatus"
}
@rhmoult
rhmoult commented Apr 21, 2015

Your Load-Packages function appears to be dead code.

@loonison101

Great example. I added a route called "/kill", and when that route GET I break out of the while loop to exit gracefully.

@pmsousa
pmsousa commented Jan 4, 2017 edited

loonison101, do you have your code anywhere?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment