Created
January 3, 2024 20:41
-
-
Save TiloGit/095bfb8cac9fe5f0512b4fda90d43a36 to your computer and use it in GitHub Desktop.
powershell mini webserver (to serve txt tile for HTTP validation for example)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
based on https://gist.github.com/19WAS85/5424431 and https://stackoverflow.com/a/63133186/1747983