脚本 手机跑.简易go服务器

termux 运行即可

Go 复制代码
package main

import (
	"log"      // 1. 导入日志包
	"net/http" // 2. 导入HTTP服务包
)

// 3. 主函数 - 程序入口点
func main() {
	// 4. 创建文件服务器,服务当前目录
	fs := http.FileServer(http.Dir("."))
	
	// 5. 注册路由处理器,使用logRequest中间件包装
	http.Handle("/", logRequest(fs))

	// 6. 打印服务启动信息
	log.Println("Listening on :8080 ...")
	
	// 7. 启动HTTP服务器,监听8080端口
	log.Fatal(http.ListenAndServe(":8080", nil))
}

// 8. logRequest 中间件函数 - 记录每个HTTP请求
// 包装下一个处理器,在请求完成后记录请求方法和路径
func logRequest(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		// 9. 创建自定义的ResponseWriter来捕获状态码
		lrw := &loggingResponseWriter{ResponseWriter: w, statusCode: 200}
		
		// 10. 调用下一个处理器
		next.ServeHTTP(lrw, r)
		
		// 11. 记录请求信息:方法、路径、状态码
		log.Printf("%s %s %d", r.Method, r.URL.Path, lrw.statusCode)
	})
}

// 12. loggingResponseWriter 结构体 - 自定义响应写入器
// 用于捕获HTTP响应的状态码
type loggingResponseWriter struct {
	http.ResponseWriter // 13. 嵌入标准ResponseWriter
	statusCode int       // 14. 存储响应状态码
}

// 15. WriteHeader 方法 - 重写写入响应头的方法
// 在写入状态码时同时记录到结构体中
func (lrw *loggingResponseWriter) WriteHeader(code int) {
	lrw.statusCode = code // 16. 保存状态码
	lrw.ResponseWriter.WriteHeader(code) // 17. 调用原始方法
}
相关推荐
金銀銅鐵5 小时前
[Python] 基于欧几里得算法,实现分数约分计算器
python·数学
Lyn_Li7 小时前
Kaggle Top 5 | 198只股票、200条数据的金融预测——BattleFin高分方案从零复现
python·kaggle·比赛复盘·金融预测
小九九的爸爸12 小时前
前端想要入门Agent开发,要具备哪些Python基础?
python·agent·ai编程
阿耶同学13 小时前
手把手教你用 LangGraph 搭建三层嵌套 Agent 架构
python·程序员
花酒锄作田1 天前
Pydantic校验配置文件
python
hboot1 天前
AI工程师第四课 - 深度学习入门
pytorch·python·神经网络
ZhengEnCi2 天前
P2M-Matplotlib折线图完全指南-从数据可视化到趋势分析的Python绘图利器
python·matlab·数据可视化
ZhengEnCi2 天前
P2L-Matplotlib饼图完全指南-从数据可视化到图表定制的Python绘图利器
python·matlab
曲幽2 天前
你的REST接口还在“过度投喂”数据吗?——FastAPI + GraphQL实战避坑指南
python·fastapi·web·graphql·route·cors·rest·strawberry
用户8358086187912 天前
基于 Self-RAG 与列表级重排序的进阶 RAG 系统设计与实现
python