如何用脚本生成迷你服务器

wen 实用脚本 3

本文目录导读:

如何用脚本生成迷你服务器

  1. Python 内置 HTTP 服务器(最简单)
  2. Node.js 迷你服务器脚本
  3. Python 多功能迷你服务器
  4. Bash 一行服务器
  5. Go 语言迷你服务器
  6. PHP 内置服务器
  7. Ruby 迷你服务器
  8. 快速选择指南

Python 内置 HTTP 服务器(最简单)

# Python 3
python3 -m http.server 8000
# Python 2
python -m SimpleHTTPServer 8000

Node.js 迷你服务器脚本

server.js:

const http = require('http');
const fs = require('fs');
const path = require('path');
const port = 3000;
const server = http.createServer((req, res) => {
  let filePath = '.' + req.url;
  if (filePath === './') filePath = './index.html';
  const extname = path.extname(filePath);
  let contentType = 'text/html';
  const mimeTypes = {
    '.html': 'text/html',
    '.js': 'text/javascript',
    '.css': 'text/css',
    '.json': 'application/json',
    '.png': 'image/png',
    '.jpg': 'image/jpg'
  };
  contentType = mimeTypes[extname] || 'text/plain';
  fs.readFile(filePath, (err, content) => {
    if (err) {
      if (err.code === 'ENOENT') {
        res.writeHead(404);
        res.end('File not found');
      } else {
        res.writeHead(500);
        res.end('Server error');
      }
    } else {
      res.writeHead(200, { 'Content-Type': contentType });
      res.end(content, 'utf-8');
    }
  });
});
server.listen(port, () => {
  console.log(`Server running at http://localhost:${port}/`);
});

运行:

node server.js

Python 多功能迷你服务器

mini_server.py:

import http.server
import socketserver
import os
import json
from urllib.parse import urlparse, parse_qs
PORT = 8000
class MiniHandler(http.server.SimpleHTTPRequestHandler):
    def do_GET(self):
        # 解析 URL
        parsed_url = urlparse(self.path)
        query_params = parse_qs(parsed_url.query)
        # API 路由
        if parsed_url.path == '/api/status':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            status = {
                'status': 'running',
                'port': PORT,
                'cwd': os.getcwd()
            }
            self.wfile.write(json.dumps(status).encode())
        else:
            # 提供静态文件
            super().do_GET()
    def do_POST(self):
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length)
        if self.path == '/api/echo':
            self.send_response(200)
            self.send_header('Content-type', 'application/json')
            self.end_headers()
            response = {'received': post_data.decode('utf-8')}
            self.wfile.write(json.dumps(response).encode())
with socketserver.TCPServer(("", PORT), MiniHandler) as httpd:
    print(f"迷你服务器运行在 http://localhost:{PORT}")
    print(f"按 Ctrl+C 停止服务器")
    httpd.serve_forever()

Bash 一行服务器

# 使用 netcat(需要安装)
while true; do nc -l -p 8080 -e echo "HTTP/1.1 200 OK\nContent-Type: text/html\n\n<h1>Hello World</h1>"; done
# 使用 socat(更强大)
socat TCP-LISTEN:8080,fork,reuseaddr SYSTEM:'echo -e "HTTP/1.1 200 OK\nContent-Type: text/html\n\n<h1>Mini Server</h1>"'

Go 语言迷你服务器

server.go:

package main
import (
    "fmt"
    "net/http"
    "log"
)
func main() {
    // 文件服务器
    http.Handle("/", http.FileServer(http.Dir("./")))
    // API 路由
    http.HandleFunc("/api/hello", func(w http.ResponseWriter, r *http.Request) {
        fmt.Fprintf(w, `{"message": "Hello from Go server!"}`)
    })
    port := ":8080"
    fmt.Printf("Server running at http://localhost%s\n", port)
    log.Fatal(http.ListenAndServe(port, nil))
}

运行:

go run server.go

PHP 内置服务器

# 当前目录作为根目录
php -S localhost:8000
# 指定路由文件
php -S localhost:8000 router.php

Ruby 迷你服务器

server.rb:

require 'webrick'
server = WEBrick::HTTPServer.new(:Port => 8080)
server.mount_proc '/' do |req, res|
  res.body = '<h1>Ruby Mini Server</h1>'
  res['Content-Type'] = 'text/html'
end
trap('INT') { server.shutdown }
server.start

运行:

ruby server.rb

快速选择指南

语言 安装要求 复杂度 适用场景
Python 通常预装 本地开发、文件共享
Node.js 需安装 Web 应用开发
Bash 类 Unix 系统 临时测试
Go 需安装 高性能服务
PHP 需安装 PHP 项目开发

最推荐python3 -m http.server 8000 - 几乎零配置,所有系统通用。

抱歉,评论功能暂时关闭!