Skip to content

练习 — net/http · Handler · Router

对应知识点:net/http · Handler · Router 对应文档:docs/phase-03-web/net-http-handler-router.md 代码目录:workspace/phase-03/net-http/

前置条件:完成 HTTP REST API 概念练习。


Level 1 — 基础

练习 1.1 · Hello HTTP 服务

workspace/phase-03/net-http/ 创建项目:

要求

  • http.HandleFunc("/", ...)ServeMux 注册根路径
  • 返回纯文本 "Digital Twin Server"
  • ListenAndServe(":8080", nil)
  • 浏览器或 curl 访问验证

练习 1.2 · JSON Handler

要求

  • GET /health 返回 {"status":"ok"}
  • 设置 Content-Type: application/json
  • 使用 json.NewEncoder(w).Encode(...)

练习 1.3 · 路径参数手动解析

要求

  • GET /api/v1/devices/{id} 使用 strings.TrimPrefix(r.URL.Path, "/api/v1/devices/") 取 id
  • 若 id 为空返回 400
  • 若 id 为 AGV-001 返回 mock JSON;否则 404

Level 2 — 应用

练习 2.1 · ServeMux 多路由

要求

  • GET /api/v1/devices — 返回设备列表 JSON 数组
  • GET /api/v1/devices/{id} — 单设备
  • POST /api/v1/devices — 读取 body 创建(mock,返回 201)
  • 使用 Go 1.22+ ServeMux 路径模式(如 GET /api/v1/devices/{id}

练习 2.2 · 请求方法校验

要求

  • 封装 methodAllowed(w, r, methods ...string) bool
  • 不支持的方法返回 405 + Allow header
  • 应用到 devices 相关路由

练习 2.3 · 统一 JSON 错误

要求

  • 函数 writeJSON(w, status, v any)
  • 函数 writeError(w, status, code, message string)
  • 所有 Handler 使用统一辅助函数

Level 3 — 综合

练习 3.1 · 内存设备 Store

要求

  • map[string]Device 内存存储
  • CRUD Handler:List、Get、Create(POST body JSON)
  • Create 时校验 id 非空、不重复
  • 适当使用 Mutex 保护 map(为并发做准备)

练习 3.2 · Handler 分层

要求

  • internal/handler/device.go — HTTP 层
  • internal/service/device.go — 业务逻辑
  • internal/store/memory.go — 存储
  • cmd/server/main.go — 路由注册与启动

Level 4 — 项目实践

练习 4.1 · Project 01 net/http 版

workspace/phase-03/net-http/ 实现 Project 01 核心 API(纯 net/http):

要求

  • GET /health
  • GET/POST /api/v1/devices
  • GET /api/v1/devices/{id}
  • GET /api/v1/devices/{id}/telemetry(返回 mock 历史数组)
  • 统一 JSON 响应与错误格式
  • go run ./cmd/server 可启动
  • README:curl 测试示例

学习检查

  • [ ] ResponseWriter 写入顺序(Header 先于 Body)?
  • [ ] 为何 Handler 应少做业务逻辑?
  • [ ] Go 1.22 ServeMux 与旧版区别?
  • [ ] 如何在不引入 Gin 的情况下组织路由?

提交方式

检查答案 — net http handler router 练习 X.X

学习导航

上一篇:HTTP and REST API · 对应知识文档 · 下一篇:Middleware、Validation、CORS