最简HTTP服务只需两步:注册路由和启动监听;需设JSON响应头、校验请求方法、正确使用中间件、显式配置超时。

用 net/http 启动最简 HTTP 服务
Go 原生 net/http 包足够轻量,不需要第三方框架就能跑起可用接口。核心就两步:注册路由 + 启动监听。
package main
<p>import (
"fmt"
"log"
"net/http"
)</p><p>func main() {
http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintln(w, "Hello from Go!")
})</p><pre class='brush:php;toolbar:false;'>log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))}
注意:http.ListenAndServe 第二个参数传 nil 表示使用默认的 http.DefaultServeMux;如果传入自定义 http.ServeMux 或 http.Handler,需确保已注册对应路径。
处理 JSON 请求和响应时别漏掉 Content-Type
很多初学者返回 JSON 时只写 json.Marshal,但前端收不到数据或解析失败,大概率是没设响应头。
立即学习“go语言免费学习笔记(深入)”;
-
w.Header().Set("Content-Type", "application/json; charset=utf-8")必须在w.WriteHeader或首次写 body 前调用 - 手动检查
r.Method,避免 GET 接口误收 POST 数据 - 用
json.NewDecoder(r.Body).Decode(&v)解析请求体,别用ioutil.ReadAll再反序列化(Go 1.16+ 已弃用ioutil)
func handleUser(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
<pre class='brush:php;toolbar:false;'>var user struct {
Name string `json:"name"`
Age int `json:"age"`
}
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
w.WriteHeader(http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(map[string]string{"status": "ok"})}
加中间件要小心 http.Handler 链的执行顺序
Go 的中间件本质是函数套函数,返回新的 http.Handler。顺序错了会导致日志不打、鉴权跳过、甚至 panic。
- 中间件包装顺序 = 执行顺序:最外层中间件最先执行,也最先收到响应
- 必须调用
next.ServeHTTP(w, r),否则后续 handler 永远不会执行 - 不要在中间件里提前
w.WriteHeader或写 body,除非你明确要终止流程(如鉴权失败)
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Started %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r) // ← 这行不能少,也不能放错位置
log.Printf("Completed %s %s", r.Method, r.URL.Path)
})
}
<p>func main() {
mux := http.NewServeMux()
mux.HandleFunc("/api/data", handleData)</p><pre class='brush:php;toolbar:false;'>// 中间件包裹:先日志,再 auth(假设存在)
handler := loggingMiddleware(authMiddleware(mux))
log.Fatal(http.ListenAndServe(":8080", handler))}
生产环境必须设超时,否则连接堆积会拖垮服务
http.ListenAndServe 默认无读写超时,一个慢客户端或恶意长连接就能让整个服务不可用。
- 用
&http.Server{}显式构造服务实例,控制ReadTimeout、WriteTimeout、IdleTimeout -
IdleTimeout控制 keep-alive 空闲连接存活时间,建议设为 30–60 秒 - 别依赖
context.WithTimeout在 handler 里做超时——那是业务逻辑超时,不是连接级防护
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
})
<pre class='brush:php;toolbar:false;'>server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 30 * time.Second,
}
log.Println("Server starting on :8080")
log.Fatal(server.ListenAndServe())}
超时值不是越小越好:太短会误杀正常慢请求;但不设,服务就等于裸奔。真实部署时,这些值得结合后端依赖(DB、RPC)的 P99 延迟来定。










