最简本地测试服务器应使用 net/http.ListenAndServe,端口设为 :0 自动分配,用 srv.Addr 获取实际地址;处理函数需独立、支持多方法及状态码;静态文件用 StripPrefix 避免路径错误;关闭时用 signal.Notify + Shutdown 实现优雅退出。

用 net/http 启一个最简本地测试服务器
不需要框架,net/http 自带的 http.ListenAndServe 就够用了。关键不是“搭服务器”,而是“让接口快速响应、方便改、不干扰主逻辑”。
常见错误是直接写死端口又不检查是否被占用,结果 listen tcp :8080: bind: address already in use 卡住;或者忘了加 log.Fatal 导致程序静默退出,以为跑起来了其实没。
- 端口建议用
:0让系统自动分配空闲端口,再用srv.Addr反查实际绑定地址 - 处理函数别直接写
func(w http.ResponseWriter, r *http.Request)匿名函数嵌套太深,拆成独立函数更易测、易调试 - 加一行
fmt.Printf("Test server running on %s\n", srv.Addr),避免盲等
package main
import (
"fmt"
"log"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"status":"ok","from":"test-server"}`))
}
func main() {
http.HandleFunc("/health", handler)
srv := &http.Server{Addr: ":0"}
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
fmt.Printf("Test server running on %s\n", srv.Addr)
select {} // 阻塞主 goroutine
}
模拟不同 HTTP 方法和返回状态码
真实调用方常会发 POST、带 Authorization 头、或故意触发 404/500。硬编码路由不够用,得靠 http.ServeMux 或手动判断 r.Method。
容易忽略的是:没设 Content-Type 头,前端 fetch 解析 JSON 失败;或者 400 响应体为空,导致客户端报 “unexpected end of JSON input”。
立即学习“go语言免费学习笔记(深入)”;
- 用
r.Method分支处理不同请求方法,比注册多个HandleFunc更灵活 - 所有非
2xx响应必须带明确Content-Type和非空响应体,否则某些 client 库会 panic - 需要读取
POSTbody 时,务必调用r.ParseForm()或io.ReadAll(r.Body),否则后续读不到
func handler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{"method":"GET"}`))
case "POST":
if err := r.ParseForm(); err != nil {
http.Error(w, `{"error":"parse form failed"}`, http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write([]byte(`{"method":"POST","data":` + string(r.PostForm.Encode()) + `}`))
default:
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
}
}
支持静态文件与 HTML 页面预览
前端联调或 UI 快速验证时,光有 API 不够,还得能访问 index.html、bundle.js。别手写 http.FileServer 路由——它默认不支持目录列表和 index.html 自动 fallback。
典型坑是:把 http.FileServer 挂在 / 下,结果覆盖了你自己的 API 路由;或者路径没加 http.StripPrefix,导致文件路径多了一级前缀打不开。
- 用
http.FileServer(http.Dir("./static"))指向本地目录,不是相对路径字符串 - 必须用
http.StripPrefix("/static/", ...)配合http.Handle("/static/", ...),否则请求/static/app.js会去读./static/static/app.js - 需要根路径
/返回index.html?单独写个 handler,不要依赖FileServer的自动索引
func staticHandler() http.Handler {
fs := http.FileServer(http.Dir("./static"))
return http.StripPrefix("/static/", fs)
}
func rootHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
http.ServeFile(w, r, "./static/index.html")
return
}
http.NotFound(w, r)
}
func main() {
http.HandleFunc("/", rootHandler)
http.Handle("/static/", staticHandler())
// ... 启动逻辑同上
关闭服务器与资源清理(避免端口残留)
本地测试频繁启停,Ctrl+C 中断后端口常被占着,下次启动直接失败。Go 的 http.Server 提供 Shutdown,但必须主动调用,且要配合信号监听。
很多人只记得 srv.Close(),但它会立刻断开连接,不等正在处理的请求结束;而 Shutdown 是优雅关闭,但若没设超时,可能永久阻塞。
- 用
signal.Notify捕获os.Interrupt(即 Ctrl+C),触发srv.Shutdown -
Shutdown必须传入带超时的context,例如context.WithTimeout(context.Background(), 5*time.Second) - 主 goroutine 别用
select{}硬等,改用sync.WaitGroup或chan os.Signal控制生命周期
func main() {
http.HandleFunc("/health", handler)
srv := &http.Server{Addr: ":0"}
go func() {
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
log.Fatal(err)
}
}()
fmt.Printf("Test server running on %s\n", srv.Addr)
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server shutdown error:", err)
}
fmt.Println("Server exited gracefully")
}
本地测试服务器的核心不是功能多,而是启动快、改得快、关得干净。端口冲突、响应头缺失、静态路径错位、关不掉残留进程——这些问题比写业务逻辑还耽误时间。把这几处逻辑拎出来单独封装,下次验证新接口,三分钟就能跑起来。










