Go 用 net/http 可直接构建高性能生产级 Web 服务;几行代码即可启动简易服务器,支持自定义 ServeMux、中间件链式封装及 context 控制超时等优化。
用 Go 写 Web 服务器非常直接,标准库 net/http 就能支撑生产级 HTTP 服务,无需额外框架也能做到高性能、低内存占用和高并发处理。
Go 自带的 http.ListenAndServe 几行代码就能启动一个服务:
示例:
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hello from Go!")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8080", nil)
}
这段代码启动了一个监听 :8080 的服务器,所有请求都由 handler 处理。它轻量、无依赖,适合 API 快速验证或微服务基础层。
标准库默认是全局单一多路复用器(http.DefaultServeMux),但实际项目中建议使用自定义 ServeMux 或更灵活的路由方式:
http.NewServeMux() 创建独立路由实例,避免全局污染HandlePrefix)和显式注册(HandleFunc("/api/users", usersHandler))/users/{id}),可引入轻量库如 gorilla/mux 或 chi,它们不破坏标准 http.Handler 接口,兼容性好Go 的 Handler 是函数式接口,天然适合链式中间件:
http.Handler 的函数,返回新 Handler
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Printf("→ %s %s\n", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
// 使用:http.ListenAndServe(":8080", loggingMiddleware(r))
点Go 的 HTTP 服务默认已很高效,但要注意几个易被忽略的细节:
w.Write() 或 json.Encoder 流式写入,减少内存拷贝http.FileServer 并启用 http.StripPrefix,别自己读文件返回http.Server 的 ReadTimeout、WriteTimeout 和 MaxHeaderBytes