-
-
Save Tim-S/c8a2273a8210f019ddf17e650ac1cc29 to your computer and use it in GitHub Desktop.
Powershell static http server
This file contains hidden or 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
#Requires -RunAsAdministrator | |
# Simple static http server. | |
Param( | |
[int]$port = 8080, | |
[string]$root = (Get-Location) | |
) | |
function Serve { | |
$listener = [System.Net.HttpListener]::new() | |
$listener.Prefixes.Add("http://+:$port/") | |
Write-Host "Root: $root" | |
try { | |
$listener.Start() | |
Write-Host "server started on :$port" | |
while ($listener.IsListening) { | |
$context = $null | |
$ctxTask = $listener.GetContextAsync() | |
do { | |
if ($ctxTask.Wait(100)) { | |
$context = $ctxTask.Result | |
} | |
} | |
while (-not $context) | |
Handle $context | |
} | |
} | |
catch [System.Exception] { | |
Write-Host $_ | |
} | |
finally { | |
$listener.Stop() | |
} | |
} | |
# import System.Web for [System.Web.MimeMapping]::GetMimeMapping | |
Add-Type -AssemblyName System.Web | |
function Handle([System.Net.HttpListenerContext] $context) { | |
try { | |
Write-Host $context.Request.RawUrl | |
$path = $context.Request.RawUrl.TrimStart("/") | |
if ([String]::IsNullOrWhiteSpace($path)) { | |
$path = "index.html" | |
} | |
$path = [System.IO.Path]::Combine($root, $path); | |
$path = [uri]::UnescapeDataString($path); | |
if ([System.IO.File]::Exists($path)) { | |
$fstream = [System.IO.FileStream]::new($path, [System.IO.FileMode]::Open, [System.IO.FileAccess]::Read) | |
# set proper Mimetype | |
$mimeType = [System.Web.MimeMapping]::GetMimeMapping($path); | |
$context.Response.ContentType = $mimeType; | |
$fstream.CopyTo($context.Response.OutputStream) | |
} else { | |
$context.Response.StatusCode = 404 | |
} | |
} | |
catch [System.Exception] { | |
$context.Response.StatusCode = 500 | |
Write-Error $_ | |
} | |
finally { | |
$context.Response.Close() | |
} | |
} | |
Serve |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment