直接用 net/http 就能跑通第一个 api,无需框架或外部模块,5 分钟内可验证成功;关键在于正确注册路由、处理端口冲突、设置 content-type,并用 httptest 编写快速单元测试。

直接用 net/http 就能跑通第一个 API,不需要框架、不依赖外部模块,5 分钟内可验证成功。
用 net/http 启动最简 HTTP 服务
Go 标准库自带完整 HTTP 能力,http.ListenAndServe 是起点。关键不是“能不能”,而是别漏掉两件事:
-
http.HandleFunc必须在ListenAndServe前注册,否则路由无效 - 端口被占用时默认 panic,建议用
:0让系统自动分配空闲端口(测试更稳定) - 响应前必须显式设置
Content-Type,否则前端可能解析失败
示例代码:
<pre class="brush:php;toolbar:false;">package main
import (
"encoding/json"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"msg": "hello from net/http"})
}
func main() {
http.HandleFunc("/ping", handler)
http.ListenAndServe(":8080", nil) // 或 ":0" 用于测试
}
测试时避免手动 curl
循环调试
每次改完代码都要切终端敲 curl http://localhost:8080/ping?太慢。真正高效的验证方式是写个测试函数,用 httptest.NewRecorder 拦住请求,不启真实网络、不占端口、秒出结果。
- 别直接传
nil给 handler ——handler(recorder, req)中的req必须是httptest.NewRequest构造的 -
recorder.Body.String()才是响应体内容,recorder.Code是状态码 - 测试文件名必须以
_test.go结尾,函数名以Test开头
最小测试片段:
<pre class="brush:php;toolbar:false;">func TestPingHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/ping", nil)
rec := httptest.NewRecorder()
handler(rec, req)
if rec.Code != 200 {
t.Errorf("expected 200, got %d", rec.Code)
}
if !strings.Contains(rec.Body.String(), "hello") {
t.Error("response body missing expected content")
}
}
POST 接口容易忽略的三处细节
GET 只要返回数据,POST 还得正确读取输入。标准库不自动解析 body,常见翻车点:
- 没调
r.ParseForm() 就直接用 <code>r.FormValue→ 返回空字符串 - JSON 请求没读
r.Body→json.Decode报invalid character - 没设
Content-Type: application/json头 → 前端发的 JSON 被当成纯文本
安全做法:对 JSON 请求,用 io.ReadAll(r.Body) 拿原始字节,再 json.Unmarshal;别依赖 r.Form。
开发阶段热重载不是必须,但能省下 10 秒重复操作
go run main.go 每次改完都要 Ctrl+C 再回车?用 air 可自动重建:
- 安装:
go install github.com/cosmtrek/air@latest - 项目根目录加
.air.toml,至少配root = "."和tmp_dir = "tmp" - 运行
air,保存文件后几秒内新进程就绪
注意:air 不处理 go.mod 变更,加新依赖后仍需手动 go mod tidy。
真正的复杂点不在启动服务,而在于错误路径——比如 POST 时 body 是空、JSON 字段类型错、URL path 多了个斜杠,这些情况标准库不会帮你兜底,必须自己检查 err 并返回明确状态码。没写这层逻辑,API 在生产环境里就只是个脆皮玩具。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











