Skip to content

Instantly share code, notes, and snippets.

@mark05e
Forked from nobodyguy/http_server.ps1
Last active July 10, 2022 20:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mark05e/089b6668895345dd274fe5076f8e1271 to your computer and use it in GitHub Desktop.
Save mark05e/089b6668895345dd274fe5076f8e1271 to your computer and use it in GitHub Desktop.
Powershell HTTP server in background thread (could be easily killed)
$listenerPort = "8007"
$ServerThreadCode = {
$listenerPort = $args[0]
$listener = New-Object System.Net.HttpListener
$listenerString = "http://+:$listenerPort/"
$listener.Prefixes.Add($listenerString)
$listener.Start()
while ($listener.IsListening) {
$context = $listener.GetContext() # blocks until request is received
$request = $context.Request
$response = $context.Response
$message = "Bad boys, bad boys whatcha gonna do? `nWhatcha gonna do when they come for you?`n"
# Show Url Path and Query in the response.
$path = $context.Request.Url.LocalPath.ToString()
$query = $context.Request.Url.Query.ToString()
if ($path){$message += "`nPath: " + $path}
if ($query){$message += "`nQuery: " + $query}
# This will terminate the script. Remove from production!
if ($request.Url -match '/end$') { break }
[byte[]] $buffer = [System.Text.Encoding]::UTF8.GetBytes($message)
$response.ContentLength64 = $buffer.length
$response.StatusCode = 200
$output = $response.OutputStream
$output.Write($buffer, 0, $buffer.length)
$output.Close()
}
$listener.Stop()
}
$serverJob = Start-Job $ServerThreadCode -ArgumentList $listenerPort
Write-Host "Listening on $listenerPort ..."
Write-Host "Try me: Invoke-WebRequest 'http://localhost:$listenerPort/hello?world'"
Write-Host "Press Ctrl+X to terminate"
[console]::TreatControlCAsInput = $true
# Wait for it all to complete
while ($serverJob.State -eq "Running")
{
if ([console]::KeyAvailable) {
$key = [system.console]::readkey($true)
if (($key.modifiers -band [consolemodifiers]"control") -and ($key.key -eq "X"))
{
Write-Host "Terminating. Please Wait.."
try { $result = Invoke-WebRequest -Uri "http://localhost:$listenerPort/end" -TimeoutSec 3 } catch { Write-Host "Listener ended" }
$serverJob | Stop-Job
Remove-Job $serverJob
break
}
}
Start-Sleep -s 1
}
# Getting the information back from the jobs
Get-Job | Receive-Job
@mark05e
Copy link
Author

mark05e commented Jul 9, 2022

Changelog

  • Add @ASfSDlS61TLT6eoP3Qb7 suggestions - Ref
  • Add listener port as a variable
  • Change termination key combo to Ctrl + X
  • Add funny message
  • Add timeout on invoke webrequest termination step
  • Add url path and query to the response message

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