用 net/http 写一个任务查询 API
用标准库实现任务查询、JSON 响应和状态码,再测试成功与失败场景。
定义接口
这个小服务提供两个 GET 接口。用 /healthz 判断进程是否响应,用 /tasks/{id} 查询任务。任务存在时返回 JSON 和 200,找不到时返回 JSON 错误和 404。
创建一个空目录,运行 go mod init example.com/taskapi。下面的路由写法需要 Go 1.22 或更高版本。
实现路由和 JSON 响应
保存为 main.go。示例启动时创建任务映射,处理请求时只读取它。
package main
import (
"encoding/json"
"log"
"net/http"
"time"
)
type Task struct {
ID string `json:"id"`
Title string `json:"title"`
Done bool `json:"done"`
}
func writeJSON(w http.ResponseWriter, status int, value any) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
if err := json.NewEncoder(w).Encode(value); err != nil {
log.Printf("write response: %v", err)
}
}
func newHandler() http.Handler {
tasks := map[string]Task{
"1": {ID: "1", Title: "运行第一个 Go 程序", Done: true},
}
mux := http.NewServeMux()
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
})
mux.HandleFunc("GET /tasks/{id}", func(w http.ResponseWriter, r *http.Request) {
task, ok := tasks[r.PathValue("id")]
if !ok {
writeJSON(w, http.StatusNotFound, map[string]string{"error": "task not found"})
return
}
writeJSON(w, http.StatusOK, task)
})
return mux
}
func main() {
server := &http.Server{
Addr: "127.0.0.1:8080",
Handler: newHandler(),
ReadHeaderTimeout: 5 * time.Second,
}
log.Printf("listening on http://%s", server.Addr)
log.Fatal(server.ListenAndServe())
}
先设置 Content-Type,再调用 WriteHeader。状态码写出后,响应头就不能再修改。用 r.PathValue("id") 读取路由匹配出的任务 ID。
在终端里触发请求
在项目目录运行 go run .,保留这个终端。在另一个终端中运行以下命令,Windows PowerShell 可用 curl.exe。
curl -i http://127.0.0.1:8080/healthz
curl -i http://127.0.0.1:8080/tasks/1
curl -i http://127.0.0.1:8080/tasks/42
前两个请求应返回 200 OK,最后一个应返回 404 Not Found 和 {"error":"task not found"}。按 Ctrl+C 停止服务。
测试 handler
将下面的测试保存为 main_test.go。测试通过 httptest 调用路由和 handler,无需绑定端口。
package main
import (
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
)
func TestGetTask(t *testing.T) {
handler := newHandler()
t.Run("found", func(t *testing.T) {
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/tasks/1", nil))
if response.Code != http.StatusOK {
t.Fatalf("status = %d; want %d", response.Code, http.StatusOK)
}
var task Task
if err := json.NewDecoder(response.Body).Decode(&task); err != nil {
t.Fatal(err)
}
if task.ID != "1" || !task.Done {
t.Errorf("unexpected task: %+v", task)
}
})
t.Run("missing", func(t *testing.T) {
response := httptest.NewRecorder()
handler.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/tasks/42", nil))
if response.Code != http.StatusNotFound {
t.Errorf("status = %d; want %d", response.Code, http.StatusNotFound)
}
})
}
运行 go test -v ./...。试着增加一条任务,再补上检查 Content-Type 和请求方法的测试。如果下一步要支持新增任务,需要同步保护映射读写,或者把数据交给数据库管理。