Golang实现一个基础的HTTP接口服务

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

net/http 启动最简 HTTP 服务

Go 原生 net/http 包足够轻量,不需要第三方框架就能跑起可用接口。核心就两步:注册路由 + 启动监听。

package main

import ( "fmt" "log" "net/http" )

func main() { http.HandleFunc("/hello", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) fmt.Fprintln(w, "Hello from Go!") })

log.Println("Server starting on :8080")
log.Fatal(http.ListenAndServe(":8080", nil))

}

注意:http.ListenAndServe 第二个参数传 nil 表示使用默认的 http.DefaultServeMux;如果传入自定义 http.ServeMuxhttp.Handler,需确保已注册对应路径。

处理 JSON 请求和响应时别漏掉 Content-Type

很多初学者返回 JSON 时只写 json.Marshal,但前端收不到数据或解析失败,大概率是没设响应头。

  • 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
    }
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)
    })
}

func main() { mux := http.NewServeMux() mux.HandleFunc("/api/data", handleData)

// 中间件包裹:先日志,再 auth(假设存在)
handler := loggingMiddleware(authMiddleware(mux))
log.Fatal(http.ListenAndServe(":8080", handler))

}

生产环境必须设超时,否则连接堆积会拖垮服务

http.ListenAndServe 默认无读写超时,一个慢客户端或恶意长连接就能让整个服务不可用。

  • &http.Server{} 显式构造服务实例,控制 ReadTimeoutWriteTimeoutIdleTimeout
  • 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)
    })
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 延迟来定。