最小可运行网站只需两步:注册路由(如http.HandleFunc("/", handler))并启动服务(http.ListenAndServe(":8080", nil)),缺一不可,否则404或panic;需注意端口占用、权限限制、请求体解析、静态文件路径及错误信息脱敏等生产要点。
用 net/http 起一个能跑的最小网站
go 原生 net/http 就够用了,不需要框架也能上线。核心就两步:注册路由、启动服务。
常见错误是直接写 http.ListenAndServe(":8080", nil) 却没调用 http.HandleFunc,结果访问 404 或 panic。
- 必须先注册 handler,比如
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("hello")) }) - 端口被占用时会报
listen tcp :8080: bind: address already in use,换端口或杀进程:lsof -i :8080(macOS/Linux)或netstat -ano | findstr :8080(Windows) - 想监听 80 或 443 需要 root 权限(Linux/macOS)或管理员权限(Windows),开发阶段别硬扛,用 8080/3000 更实际
处理表单和 JSON 请求得手动解析
Go 不像 Python 或 Node.js 那样自动解包请求体,ParseForm 和 json.Decode 是绕不开的。
典型坑:对 POST 请求忘记调用 r.ParseForm() 就直接读 r.FormValue,结果始终为空;或者用 json.Unmarshal 解析前没读完整 body,导致 EOF 错误。
- 表单数据:在 handler 里加
r.ParseForm(),再用r.FormValue("name") - JSON 数据:用
json.NewDecoder(r.Body).Decode(&v),别用ioutil.ReadAll再解,容易漏关 body - 注意 Content-Type:前端发 JSON 时必须设
Content-Type: application/json,否则 Go 不会拒绝但你拿不到数据
静态文件用 http.FileServer,但路径别写错
放 CSS/JS/图片?别手写读文件逻辑,直接用 http.FileServer,但它对路径很敏感。
使用 uber-go/dig 在 Golang 中实现依赖注入——基于反射容器,提供 Provide/Invoke、dig.In/dig.Out 参数与结果对象,支持命名依赖等
错误示例:http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static")))) —— 看似没问题,但如果当前工作目录不是项目根目录,./static 就找不到。
- 推荐用绝对路径:
http.Dir(filepath.Join(os.Getenv("PWD"), "static"))(Linux/macOS)或http.Dir(filepath.Join(os.Getenv("CD"), "static"))(Windows) - 更稳妥的是用
runtime.Caller定位源码目录,比如filepath.Dir(filepath.Dir(filepath.Dir(runtime.Caller(0)))),再拼"static" - 浏览器访问
/static/style.css时,实际读的是./static/style.css,不是./static/static/style.css——StripPrefix的作用就是去掉 URL 前缀,别多删或多留
上线前记得关掉 http.Error 泄露细节
开发时用 http.Error(w, err.Error(), http.StatusInternalServerError) 很方便,但上线后会把堆栈、路径、数据库名全打出来。
真实环境必须拦截错误,只返回通用提示,否则等于送攻击者情报。
- 简单做法:所有 handler 外层套
defer func() { if r := recover(); r != nil { http.Error(w, "Internal Error", http.StatusInternalServerError) } }() - 更合理的是用中间件包装 handler,统一处理 error 类型,对
sql.ErrNoRows返回 404,对校验失败返回 400 - 日志另存:用
log.Printf记详细错误,但响应体里只写"Something went wrong"
golang免费学习笔记(深入):立即使用
在学习笔记中,你将探索golang的核心概念和高级技巧!










