

新闻资讯
技术学院最常见原因是监听地址写成了"localhost:8080"或"127.0.0.1:8080",应改用":8080"监听所有接口;此外需检查端口占用、Docker映射、路由前缀匹配逻辑、JSON解析时机及生产环境应使用http.Server而非ListenAndServe。
http.ListenAndServe 启动后没报错却访问不了?最常见原因是监听地址写成了 "localhost:8080" 或 "127.0.0.1:8080",导致外部网络(包括 Docker 容器外、云服务器安全组外)无法连接。Go 的 net/http 默认只绑定到本地回环地址。
":8080"(空主机名),表示监听所有可用网络接口http.ListenAndServe 会返回 "address already in use" 错误;但若监听成功却无响应,优先检查绑定地址EXPOSE 和宿主机 -p 映射是否匹配http.ServeMux 实现路径路由?http.ServeMux 是 Go 标准库默认的 HTTP 路由器,支持前缀匹配而非完全匹配,这点容易引发意料外的行为。
"/api" 会匹配 /api、/api/users、甚至 /apixxx —— 因为它只是字符串前缀判断r.URL.Path,或改用第三方路由器(如 gorilla/mux、chi)func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("ok"))
})
// 注意:这个会匹配 /api 和 /api/xxx,但不会匹配 /apiuser
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/api/" {
http.Error(w, "use subpath", http.StatusBadRequest)
return
}
w.Write([]byte("data"))
})
http.ListenA
ndServe(":8080", mux)
}
i/o timeout 或 invalid character?直接调用 json.Decode(r.Body) 前,必须确保 r.Body 没被其他逻辑提前读取(比如日志中间件调用了 r.Body.Read 或 io.ReadAll),否则后续解码会得到空内容或 EOF。
r.Header.Get("Content-Type") 检查是否为 "application/json",避免非 JSON 请求触发解析错误json.NewDecoder 而非 json.Unmarshal 可减少内存拷贝,但两者都要求 body 可读一次http.Server.ReadTimeout
type User struct {
Name string `json:"name"`
Age int `json:"age"`
}
func createUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, "content-type must be application/json", http.StatusBadRequest)
return
}
var u User
decoder := json.NewDecoder(r.Body)
if err := decoder.Decode(&u); err != nil {
http.Error(w, "invalid json: "+err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "created"})
}
http.ListenAndServe?标准 http.ListenAndServe 启动的 server 缺少对优雅关闭、超时控制、连接限制等关键生产特性的配置能力。一旦进程收到 SIGINT/SIGTERM,它会立即退出,正在处理的请求可能被中断。
立即学习“go语言免费学习笔记(深入)”;
http.Server 结构体显式构造,并设置 ReadTimeout、WriteTimeout、IdleTimeout
srv.Shutdown(),配合 context.WithTimeout 等待活跃连接完成真正上线时,http.ListenAndServe 只适合原型验证——它掩盖了连接生命周期管理的复杂性。