脚本 手机跑.简易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. 调用原始方法
}
相关推荐
Tony Bai3 小时前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
秃了也弱了。4 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
Dfreedom.4 小时前
从 model(x) 到__call__:解密深度学习框架的设计基石
人工智能·pytorch·python·深度学习·call
weixin_425023004 小时前
Spring Boot 配置文件优先级详解
spring boot·后端·python
小徐Chao努力5 小时前
【Langchain4j-Java AI开发】06-工具与函数调用
java·人工智能·python
无心水5 小时前
【神经风格迁移:全链路压测】33、全链路监控与性能优化最佳实践:Java+Python+AI系统稳定性保障的终极武器
java·python·性能优化
luoluoal6 小时前
基于python的小区监控图像拼接系统(源码+文档)
python·mysql·django·毕业设计·源码
BoBoZz197 小时前
MotionBlur 演示简单运动模糊
python·vtk·图形渲染·图形处理
十八度的天空7 小时前
第01节 Python的基础语法
开发语言·python
BoBoZz197 小时前
GradientBackground 比较不同类型的背景渐变着色模式与坐标转换
python·vtk·图形渲染·图形处理