使用 HTTP 构建服务器有多种方式,以下是几种常见的方法:
1.使用 Python 内置模块(最简单)
python -m http.server 8000 或指定目录 python -m http.server 8000 --directory /path/to/serve
from http.server import HTTPServer, SimpleHTTPRequestHandler
简单静态文件服务器
server = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
print("服务器运行在 http://localhost:8000")
server.serve_forever()2.使用 Node.js 的 http 模块
const http = require('http');
const fs = require('fs');
const path = require('path');
const server = http.createServer((req, res) => {
// 处理请求
if (req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end('<h1>欢迎访问服务器</h1>');
} else if (req.url === '/api/data') {
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ message: 'Hello World' }));
} else {
res.writeHead(404);
res.end('Not Found');
}
});
server.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});3.使用 Express.js(Node.js 框架)
npm init -y npm install express
const express = require('express');
const app = express();
// 静态文件服务
app.use(express.static('public'));
// API 路由
app.get('/', (req, res) => {
res.send('Hello World!');
});
app.get('/api/users', (req, res) => {
res.json([{ id: 1, name: '张三' }]);
});
app.listen(3000, () => {
console.log('服务器运行在 http://localhost:3000');
});4.使用 Go 语言
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello, %s!", r.URL.Path[1:])
}
func main() {
http.HandleFunc("/", handler)
http.HandleFunc("/api", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w,{"status": "ok"})
})
fmt.Println("服务器运行在 http://localhost:8080")
http.ListenAndServe(":8080", nil)
}5.使用 Nginx(生产环境推荐)
nginx.conf 示例
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
location /api/ {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
}
}6.使用 Apache HTTP Server
httpd.conf 或 .htaccess
DocumentRoot "/var/www/html"
<Directory "/var/www/html">
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>快速创建服务器的工具
使用 serve(Node.js 静态服务器)
npm install -g serve serve -l 5000
npm install -g http-server http-server -p 8080
完整示例:Python 多功能服务器
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
class RequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == '/':
self.send_response(200)
self.send_header('Content-Type', 'text/html')
self.end_headers()
self.wfile.write(b'<h1>主页</h1>')
elif self.path == '/api/data':
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
response = json.dumps({"message": "Hello", "status": "ok"})
self.wfile.write(response.encode())
else:
self.send_error(404)
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
# 处理POST数据
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
response = json.dumps({"received": True, "data": post_data.decode()})
self.wfile.write(response.encode())
def run(server_class=HTTPServer, handler_class=RequestHandler):
server_address = ('', 8000)
httpd = server_class(server_address, handler_class)
print('服务器运行在 http://localhost:8000')
httpd.serve_forever()
if __name__ == '__main__':
run()生产环境建议
1、安全性
- 使用 HTTPS(Let's Encrypt 免费证书)
- 设置适当的 CORS 头
- 防止 SQL 注入和 XSS 攻击
2、性能优化
- 启用 gzip 压缩
- 使用 CDN 静态资源
- 设置缓存头
3、部署工具
Docker:容器化部署
PM2:Node.js 进程管理
systemd:Linux 服务管理
选择哪种方式取决于你的需求:
快速测试:Pythonhttp.server
Web 应用:Node.js + Express
高性能:Go 或 Rust
生产环境:Nginx/Apache + 应用服务器
文章摘自:https://idc.huochengrm.cn/fwq/24963.html
评论