Skip to content

Instantly share code, notes, and snippets.

@DrMeosch
Created December 4, 2019 18:19
Show Gist options
  • Select an option

  • Save DrMeosch/e288c62b9c9dde36fe6bc6f0371fc7fb to your computer and use it in GitHub Desktop.

Select an option

Save DrMeosch/e288c62b9c9dde36fe6bc6f0371fc7fb to your computer and use it in GitHub Desktop.
# You Should be able to Copy and Paste this into a powershell terminal and it should just work.
# To end the loop you have to kill the powershell terminal. ctrl-c wont work :/
# Http Server
$http = [System.Net.HttpListener]::new()
# Hostname and port to listen on
# PS> netsh http add urlacl url="http://+:4200/" user=everyone
$Http.Prefixes.Add("http://+:4200/")
# Start the Http Server
$http.Start()
# Log ready message to terminal
if ($http.IsListening) {
write-host " HTTP Server Ready! " -f 'black' -b 'gre'
}
# INFINTE LOOP
# Used to listen for requests
while ($http.IsListening) {
# Get Request Url
# When a request is made in a web browser the GetContext() method will return a request object
# Our route examples below will use the request object properties to decide how to respond
$context = $http.GetContext()
if ($context.Request.HttpMethod -eq 'GET' -and $context.Request.RawUrl -eq '/') {
# We can log the request to the terminal
write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag'
# the html/data you want to send to the browser
# you could replace this with: [string]$html = Get-Content "C:\some\path\index.html" -Raw
[string]$html = "<h1>A Powershell Webserver</h1><p>home page</p>"
#resposed to the request
$buffer = [System.Text.Encoding]::UTF8.GetBytes($html) # convert htmtl to bytes
$context.Response.ContentLength64 = $buffer.Length
$context.Response.OutputStream.Write($buffer, 0, $buffer.Length) #stream to broswer
$context.Response.OutputStream.Close() # close the response
}
# ROUTE EXAMPLE 2
# http://localhost:8080/some/form'
if ($context.Request.HttpMethod -eq 'GET' -and $context.Request.RawUrl -ne '/') {
# We can log the request to the terminal
write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag'
$FileName = [string](Get-Location) + '\' + $context.Request.RawUrl.Substring(1);
$buffer = [IO.File]::ReadAllBytes($FileName)
#resposed to the request
# $buffer = [System.Text.Encoding]::UTF8.GetBytes($html)
$context.Response.ContentLength64 = $buffer.Length
$context.Response.ContentType = "application/x-binary";
$context.Response.OutputStream.Write($buffer, 0, $buffer.Length)
$context.Response.OutputStream.Close()
break
}
# powershell will continue looping and listen for new requests...
}
# $context.Response.Close()
$http.Stop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment