最简HTTP服务用http.ListenAndServe(":8080", nil),注册路由优先选http.HandleFunc;HTTPS需用ListenAndServeTLS并提供证书;生产环境应显式创建http.Server以支持超时控制和优雅关机。
net/http 启动最简服务Go 内置的 net/http 包足够直接跑起一个可用的 HTTP 服务,不需要额外依赖。核心就是调用 http.ListenAndServe,传入监听地址和处理器。
"host:port",比如 ":8080"(空 host 表示监听所有接口);写成 "8080" 会报错 listen tcp: address 8080: missing port in address
nil,此时使用默认的 http.DefaultServeMux;也可以传自定义的 http.Handler 实例listen tcp :8080: bind: address already in use
package main
import (
"fmt"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, World!")
})
http.ListenAndServe(":8080", nil)
}
http.HandleFunc 还是 http.Handle?两者都注册到默认多路复用器,区别在于参数类型和灵活性:
http.HandleFunc(pattern, handlerFunc):第二个参数是 func(http.ResponseWriter, *http.Request),写起来更简洁http.Handle(p
attern, handler):第二个参数必须是实现了 http.Handler 接口的类型(含 ServeHTTP 方法),适合封装逻辑或复用中间件"/api" 会匹配 "/api/users" 和 "/api",但不会自动区分末尾斜杠;若需精确匹配,得自己在 handler 里判断 r.URL.Path
用 http.ListenAndServeTLS 替代 ListenAndServe,它要求提供 TLS 证书文件路径:
":443"
cert.pem)和私钥文件(key.pem)路径;路径必须可读,否则报错 open cert.pem: no such file or directory
http.Server 实例,分别绑定不同端口和配置err := http.ListenAndServeTLS(":443", "cert.pem", "key.pem", nil)
if err != nil {
panic(err)
}
http.Server 实例?直接调用 http.ListenAndServe 看似简单,但缺少对超时、连接生命周期、优雅关闭等关键控制。显式构造 http.Server 是生产环境的标准做法:
ReadTimeout 和 WriteTimeout 防止慢请求拖垮服务(注意:Go 1.8+ 推荐用 ReadHeaderTimeout 和 IdleTimeout 更精细)context.Context 可实现优雅关机:调用 srv.Shutdown(ctx) 会等待活跃连接完成再退出Handler、Addr、TLS 配置等,便于测试和复用Handler 链中很多线上崩溃不是因为业务逻辑错,而是没设超时或没做关机等待,导致 SIGTERM 后连接被粗暴中断。