一键静态WEB服务器

admin
admin 4月2日
  • 在其它设备中阅读本文章

简化 HTTP 服务器的配置和管理,使用系统自带的服务,无需安装任何东西,将指定目录作为 HTTP 服务器的根目录,一键开启静态服务器

实现原理

Window10 和 Window11 自带 PowerShell,使用 HttpListener 类创建 HTTP 服务,绑定端口接收请求并返回指定文件。Linux 系统自带 python,用 http.server 模块即可创建简易的 HTTP 服务器。

Windows 系统实现

创建 server.ps1 文件,并写入如下内容

# PowerShell Web Server
Param(
    [parameter(Mandatory=$false)][Int]$port=8080,
    [parameter(Mandatory=$false)][String]$webPath="www"
)

Add-Type -AssemblyName System.Web

$scriptPath = $PSScriptRoot

$http = [System.Net.HttpListener]::new()
$http.Prefixes.Add("http://localhost:$port/")
$http.Start()

function ConvertTo-Base64($str){
    $result = [Convert]::ToBase64String([System.Text.UTF8Encoding]::UTF8.GetBytes($str))
    return $result
}

function ConvertFrom-Base64($str){
    $byteArray = [Convert]::FromBase64String($str)
    return [System.Text.UTF8Encoding]::UTF8.GetString($byteArray)
}

function Send-WebResponse($context, $content) {
    if($content.GetType().Name -ne "String"){
        $content = ConvertTo-JSON $content
    }
    $buffer = [System.Text.Encoding]::UTF8.GetBytes($content)
    $context.Response.ContentLength64 = $buffer.Length
    $context.Response.OutputStream.Write($buffer, 0, $buffer.Length)
}

function Get-PostData{
    $reader = new-object System.IO.StreamReader($context.Request.InputStream)
    $text = $reader.ReadToEnd()
    # $text = $text.Replace("%3D","=")
    # $text = ConvertFrom-Base64 $text
    $text = [System.Web.HttpUtility]::UrlDecode($text)
    Write-Host "$text"
    return ConvertFrom-Json $text
}

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) {
    $context = $http.GetContext()
    $RequestUrl = $context.Request.Url.LocalPath
    
    Write-Host "$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) : $($context.Request.Url)" -f 'mag'

    # Get Request Url
    if ($context.Request.HttpMethod -eq 'GET') {       
        # Redirect root to index.html
        if($RequestUrl -eq "/") {
          $RequestUrl = "/index.html"
        }
        if(Test-Path "$scriptPath\$webPath\$RequestUrl"){
            $fileStream = [System.IO.File]::OpenRead( "$scriptPath\$webPath\$RequestUrl" )
            $fileStream.CopyTo( $Context.Response.OutputStream )
            $fileStream.Close()
        }
        else{
            Send-WebResponse $context "404 : Not found $RequestUrl"            
        }
        $context.Response.Close()
    }
}

脚本接收两个参数,第一个是绑定端口,默认为 8080,第二个是指定根目录,默认为当前目录下的 www\ 目录。打开 PowerShell 窗口,执行.\server.ps1,也可以右键菜单使用 PowerShell 执行此脚本,出现下图窗口表示执行成功,关闭窗口就可以关闭 HTTP 服务器。如果遇到执行异常,可以管理员身份打开 PowerShell,运行命令Set-ExecutionPolicy RemoteSigned解锁 ps1 脚本执行权限(系统默认没有开启)。
powershell.png

为了方便,可以创建如下内容的的 start.bat 文件,一键开启静态服务器,无需管理员身份,也没有权限问题。

if "%1" neq "" (set port=%1) else (set port=8080)
if "%2" neq "" (set root=%2) else (set root=www)

start http://localhost:%port%
powershell -ExecutionPolicy RemoteSigned .\server.ps1 %port% %root%

Linux 系统实现

相比 Windows 系统简单许多,Linux 系统默认已经安装 python,使用 http.server 模块,一条命令可启动。绑定本地网卡地址,监听 8080 端口,使用 www 作为根目录,开启 HTTP 服务器的命令如下。

python -m http.server 8080 -b localhost -d www

可选参数说明

  1. -b:指定绑定网卡地址,默认为 0.0.0.0,不安全,可更改为 localhost
  2. -d:指定根目录,默认为当前目录

为了方便,可以创建如下内容的的 start.sh 文件,一键开启静态服务器。

#!/bin/bash

xdg-open http://localhost:8080
python -m http.server 8080 -b localhost -d www