Skip to content

Instantly share code, notes, and snippets.

@TiloGit
Created January 3, 2024 20:41
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 TiloGit/095bfb8cac9fe5f0512b4fda90d43a36 to your computer and use it in GitHub Desktop.
Save TiloGit/095bfb8cac9fe5f0512b4fda90d43a36 to your computer and use it in GitHub Desktop.
powershell mini webserver (to serve txt tile for HTTP validation for example)
$basePath='C:\mini-webserver\'
mkdir -p "$basePath/web/.well-known/pki-validation/"
##paste the txt file to this location
$http = [System.Net.HttpListener]::new()
# Hostname and port to listen on
##port 80 requires admin PS
$http.Prefixes.Add("http://+:80/")
# Start the Http Server
$http.Start()
Add-Type -AssemblyName System.Web
# Log ready message to terminal
if ($http.IsListening) {
write-host "HTTP Server Ready! " -f 'black' -b 'gre'
write-host "$($http.Prefixes)" -f 'y'
}
# 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') {
# We can log the request to the terminal
write-host "$($context.Request.UserHostAddress) => $($context.Request.Url)" -f 'mag'
$URL = $context.Request.Url.LocalPath
# Redirect root to index.html
if($URL -eq "/") {
$URL = "/index.html"
}
$ContentStream = [System.IO.File]::OpenRead( "$basePath/web/$URL" );
$context.Response.Headers.Add("Content-Type", "text/plain")
#$Context.Response.ContentType = [System.Web.MimeMapping]::GetMimeMapping("$basePath/web/$URL")
$ContentStream.CopyTo( $Context.Response.OutputStream );
$Context.Response.Close()
}
# powershell will continue looping and listen for new requests...
}
@TiloGit
Copy link
Author

TiloGit commented Jan 3, 2024

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