Created
September 16, 2025 05:04
-
-
Save ledsun/f9c16bd464c2c15e80199771b169e4aa to your computer and use it in GitHub Desktop.
簡易HTTPサーバーとして動作するPoweShellスクリプト
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
$port = 8000 | |
$root = (Get-Location).Path | |
$listener = [System.Net.HttpListener]::new() | |
# 権限設定が不要なローカル限定にするなら: | |
$prefix = "http://localhost:$port/" | |
# どのIPでも受けたい場合は URLACL 必要: $prefix = "http://+:$port/" | |
$listener.Prefixes.Add($prefix) | |
$listener.Start() | |
Write-Host "Serving $root at $prefix (Ctrl+C で停止)" | |
try { | |
while ($listener.IsListening) { | |
$ctx = $null | |
try { | |
$ctx = $listener.GetContext() | |
$requestPath = $ctx.Request.Url.LocalPath.TrimStart('/') | |
if ([string]::IsNullOrWhiteSpace($requestPath)) { $requestPath = 'index.html' } | |
$file = Join-Path -Path $root -ChildPath $requestPath | |
if (Test-Path -LiteralPath $file -PathType Leaf) { | |
$bytes = [System.IO.File]::ReadAllBytes($file) | |
$ctx.Response.StatusCode = 200 | |
# MIME を付けておくとブラウザで開きやすい | |
try { $ctx.Response.ContentType = [System.Web.MimeMapping]::GetMimeMapping($file) } catch {} | |
$ctx.Response.ContentLength64 = $bytes.Length | |
$ctx.Response.OutputStream.Write($bytes, 0, $bytes.Length) | |
} else { | |
$msg = "Not found: /$requestPath" | |
$bytes = [System.Text.Encoding]::UTF8.GetBytes($msg) | |
$ctx.Response.StatusCode = 404 | |
$ctx.Response.ContentType = "text/plain; charset=utf-8" | |
$ctx.Response.ContentLength64 = $bytes.Length | |
$ctx.Response.OutputStream.Write($bytes, 0, $bytes.Length) | |
} | |
} catch { | |
Write-Warning $_ | |
if ($ctx -and $ctx.Response) { | |
try { $ctx.Response.StatusCode = 500 } catch {} | |
} | |
} finally { | |
if ($ctx -and $ctx.Response) { | |
try { $ctx.Response.OutputStream.Close() } catch {} | |
try { $ctx.Response.Close() } catch {} | |
} | |
} | |
} | |
} finally { | |
try { $listener.Stop() } catch {} | |
try { $listener.Close() } catch {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment