用 net/http 可构建可用 Web 服务,但需手动处理错误、超时、中间件和并发安全;推荐显式使用 http.ServeMux 管理路由,配合 http.Server 设置超时与优雅关闭,并注意 JSON 处理、资源释放等细节。
用 net/http 就能跑起来一个可用的 Web 服务,不需要框架也能处理路由、JSON 响应、表单解析——但得手动管好错误、超时、中间件和并发安全。
http.ListenAndServe 启动最简服务这是所有 Go Web 服务的起点。它默认使用 http.DefaultServeMux,但直接用它写路由容易混乱,尤其当 handler 多了以后。
http.ListenAndServe 第二个参数传 nil 表示用默认 multiplexer,不推荐用于生产listen tcp :8080: bind: address already in use,建议加 net.Listen 预检或换端口http.Server 结构体 + Shutdown
package mainimport ( "fmt" "net/http" )
func main() { http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprint(w, "Hello, World!") }) fmt.Println("Server starting on :8080") http.ListenAndServe(":8080", nil) }
http.ServeMux 显式管理路由显式创建 http.ServeMux 能避免全局状态污染,也方便单元测试(可传入 mock request/response)。
ServeMux 不支持路径参数(如 /user/:id),只认前缀匹配,/user/123 和 /user/abc 都会命中 /user/
http: multiple registrations for /path
/api 不会匹配 /api/users,但 /api/ 会package mainimport ( "fmt" "net/http" )
func main() { mux := http.NewServeMux() mux.HandleFunc("/health", func(w http.ResponseWriter, r http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprint(w, "OK") }) mux.HandleFunc("/api/", func(w http.ResponseWriter, r http.Request) { fmt.Fprintf(w, "API prefix: %s", r.URL.Path) })
http.ListenAndServe(":8080", mux)}
用
http.Server控制超时与关闭裸调
ListenAndServe没法设读写超时,也没法在进程信号到来时等待已有请求完成再退出——这在部署时极易导致 502 或连接中断。
ReadTimeout 和 WriteTimeout 是基础防护,但更推荐用 ReadHeaderTimeout + IdleTimeout 组合,防慢速攻击Shutdown 需配合 context 使用,超时后强制终止未完成请求;注意 handler 内部不能忽略 ctx.Done()
":8080" 表示所有接口,若只想本地访问,改用 "127.0.0.1:8080"
package mainimport ( "context" "fmt" "net/http" "os" "os/signal" "syscall" "time" )
func main() { mux := http.NewServeMux() mux.HandleFunc("/", func(w http.ResponseWriter, r http.Request) { time.Sleep(2 time.Second) // 模拟耗时操作 fmt.Fprint(w, "Done") })
server := &http.Server{ Addr: ":8080", Handler: mux, ReadTimeout: 5 * time.Second, WriteTimeout: 10 * time.Second, } done := make(chan error, 1) go func() { done <- server.ListenAndServe() }() sig := make(chan os.Signal, 1) signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) <-sig ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() server.Shutdown(ctx) fmt.Println("Server stopped")}
JSON 响应与请求解析的常见陷阱
Go 的
json包默认只序列化导出字段(首字母大写),且对空值、零值、嵌套结构的处理容易出错。
Content-Type: application/json; charset=utf-8,前端可能解析失败json.Unmarshal 解析请求体前,必须先调用 r.Body.Close()(虽然常被忽略,但泄漏 fd 会导致服务卡死)json.RawMessage 适合延迟解析嵌套 JSON 字段,避免定义大量 struct;但别忘了它本身不是字符串,打印要转 string()
time.Time 接收时,输入格式必须是 RFC3339(如 "2025-01-01T00:00:00Z"),否则解码失败不报错,而是设为零值package mainimport ( "encoding/json" "fmt" "net/http" "time" )
type User struct { ID int
json:"id"Name stringjson:"name"CreatedAt time.Timejson:"created_at"}func main() { http.HandleFunc("/user", func(w http.ResponseWriter, r *http.Request) { if r.Method == "POST" { var u User if err := json.NewDecoder(r.Body).Decode(&u); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } defer r.Body.Close() // 关键:防止文件描述符泄漏
w.Header().Set("Content-Type", "application/json; charset=utf-8") json.NewEncoder(w).Encode(map[string]interface{}{"status": "ok", "data": u, }) } }) http.ListenAndServe(":8080", nil)
}
真正难的不是写 handler,而是让每个请求都带上 trace ID、做结构化日志、验证 JWT、限流、重试、指标暴露——这些都不在
net/http里,得自己搭或者选轻量库。别急着封装“通用 router”,先确保超时、错误返回、body 关闭、content-type 这几件事每次都不忘。
来电咨询