$listener = [System.Net.HttpListener]::new()
$listener.Prefixes.Add("http://localhost:8080/")
$listener.Start()
while ($listener.IsListening) {
# Get Request Url
# When a request is made in a web browser the GetContext() method will retuen the request url
# Our routes will use this to decide how to respond
$context = $listener.GetContext()
# ROUTE EXAMPLE 1
if ($context.Request.RawUrl -eq '/') {
# the html/data you want to send to the browser
# you could replace this with Get-Content "C:\some\path\index.html"
[string]$content = "<h1>A Powershell Webserver</h1><p>Root Route</p>"
#resposed to the request and
$response = $context.Response
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content) # convert htmtl to bytes
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length) #stream to broswer
$response.OutputStream.Close() # close the respose
}
# ROUTE EXAMPLE 2
if ($context.Request.RawUrl -eq '/some/path') {
# the html/data you want to send to the browser
# you could replace this with Get-Content "C:\some\path\index.html"
[string]$content = "<h1>A Powershell Webserver</h1><p>Some Other Route</p>"
#resposed to the request and
$response = $context.Response
$buffer = [System.Text.Encoding]::UTF8.GetBytes($content) # convert htmtl to bytes
$response.ContentLength64 = $buffer.Length
$response.OutputStream.Write($buffer, 0, $buffer.Length) #stream to broswer
$response.OutputStream.Close() # close the respose
}
# powershell will continue looping and listen for new requests...
}