用 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/ - 注册重复路径会 panic,错误信息是
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)}
立即学习“go语言免费学习笔记(深入)”;
用
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")}
立即学习“go语言免费学习笔记(深入)”;
JSON 响应与请求解析的常见陷阱
Go 的
json包默认只序列化导出字段(首字母大写),且对空值、零值、嵌套结构的处理容易出错。
- 响应 JSON 时忘记设
Content-Type: application/json; charset=utf-8,前端可能解析失败 - 用
json.Unmarshal解析请求体前,必须先调用r.Body.Close()(虽然常被忽略,但泄漏 fd 会导致服务卡死) -
json.RawMessage适合延迟解析嵌套 JSON 字段,避免定义大量 struct;但别忘了它本身不是字符串,打印要转string() - 时间字段用
time.Time接收时,输入格式必须是 RFC3339(如"2024-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)}
立即学习“go语言免费学习笔记(深入)”;
真正难的不是写 handler,而是让每个请求都带上 trace ID、做结构化日志、验证 JWT、限流、重试、指标暴露——这些都不在
net/http里,得自己搭或者选轻量库。别急着封装“通用 router”,先确保超时、错误返回、body 关闭、content-type 这几件事每次都不忘。










