Created
January 11, 2023 06:58
-
-
Save t2psyto/be8916110777a5fb68e396676eed47c2 to your computer and use it in GitHub Desktop.
HttpServer.ps1.bat. need to exec as administorator
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
<# : by earthdiver1 | |
@echo off | |
cd %~dp0 | |
set BATCH_ARGS=%* | |
setlocal EnableDelayedExpansion | |
set "BATCH_ARGS=!BATCH_ARGS:%%=%%%%!" | |
set "PWSH_ARGS=" & call :quote_args !BATCH_ARGS! | |
Powershell -NoProfile -Command "$input|&([ScriptBlock]::Create((gc '%~f0'|Out-String)))" !PWSH_ARGS! | |
endlocal | |
pause & exit/b | |
:quote_args | |
set "BATCH_ARG=" & call set "BATCH_ARG=%%1" 2>nul | |
if defined BATCH_ARG goto :arg_exists | |
set BATCH_ARG=%1 | |
if not defined BATCH_ARG goto :eof | |
rem "&" or ">" or "<" is included | |
set "BATCH_ARG=!BATCH_ARG:^^=^!" | |
:arg_exists | |
set "BATCH_ARG=!BATCH_ARG:\"=\\"!" | |
set "BATCH_ARG=!BATCH_ARG:"=\"!" | |
set "BATCH_ARG=!BATCH_ARG:'=''!" | |
set "PWSH_ARGS=!PWSH_ARGS! "'!BATCH_ARG!'"" | |
shift & goto :quote_args | |
: #> | |
#以下にPowerShellスクリプトを書く | |
try { | |
$listener = new-object Net.HttpListener | |
$listener.Prefixes.Add("http://+:8888/") | |
$listener.Start() | |
echo "Server is running at port 8888" | |
function ContentType ($ext) | |
{ | |
switch ($ext) | |
{ | |
".html" { "text/html" } | |
".js" { "text/javascript" } | |
".css" { "text/css" } | |
".json" { "application/json" } | |
".xml" { "text/xml" } | |
".gif" { "image/gif" } | |
".ico" { "image/x-icon" } | |
".jpg" { "image/jpeg" } | |
".png" { "image/png" } | |
".svg" { "image/svg+xml" } | |
".webp" { "image/webp" } | |
".zip" { "application/zip" } | |
".webp" { "image/webp" } | |
Default { "text/plain" } | |
} | |
} | |
while ($true) | |
{ | |
$context = $listener.GetContext() | |
$path = $context.Request.Url.AbsolutePath | |
if ($path.EndsWith("/")) { | |
$path += "index.html" | |
} | |
$filepath = join-path (get-location) $path | |
$exists = [IO.File]::Exists($filepath) | |
echo "$($path) --> $($filepath) [$($exists)]" | |
if ($exists) { | |
$extension = [IO.Path]::GetExtension($filepath) | |
$context.Response.ContentType = ContentType($extension) | |
$rstream = [IO.File]::OpenRead($filepath) | |
$stream = $context.Response.OutputStream | |
$rstream.CopyTo($stream) | |
$stream.Close() | |
$rstream.Dispose() | |
} else { | |
$context.Response.ContentType = "text/html" | |
$context.Response.StatusCode = 404 | |
$content = [Text.Encoding]::UTF8.GetBytes("File Not Found") | |
$stream = $context.Response.OutputStream | |
$stream.Write($content, 0, $content.Length) | |
$stream.Close() | |
} | |
} | |
} catch { | |
Write-Error $_.Exception | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment