第 7 章 · 网络基础与 curl/wget
本章目标:看懂本机 IP 与 监听端口;用 curl 调试 HTTP API(GET/POST/JSON);用 wget 下载文件;搞懂 Connection refused 与 Could not resolve 分别该查什么;为 ch14 部署后的 healthz 检查打基础。
学时建议:3.5~4 小时(含 2 小时跟练)
前置:完成 linux-shell ch06;API_PORT=8080 已在 .env.local 里(可选)。
7.1 场景说明:服务明明 systemctl 是 active,浏览器却打不开
ch05 你把 shop-demo-heartbeat 跑起来了,systemctl status 显示 active (running)。同事问:「API 端口 8080 通不通?」
你打开浏览器输入 localhost:8080——若 api-go-demo 还没部署(ch14),会连不上。此时需要会:
- 本机到底有没有程序在听 8080?→ ss
- 用命令行发 HTTP 请求,不依赖浏览器 → curl
- 报
Connection refused还是超时?→ 两条完全不同的排查路
本章在 公网 httpbin 上练 curl,再在本机练 端口与 hosts,最后模拟 ch14 的 healthz 检查。
7.2 学完你能
| 能力 | 验收 |
|---|---|
| 读 IP | ip -br addr 说出 WSL/VM 的 IPv4 |
| 查监听端口 | ss -tlnp 找到 :8080 对应进程 |
| curl GET | 对 httpbin 拿到 200 和 JSON |
| curl POST | 发送 slug+price JSON body |
| 读 curl -v | 说出请求行、响应码、Header 大概位置 |
| 排查 refused | 区分「没进程听」和「防火墙挡」 |
| wget | 下载小文件到 ~/dev-workspace |
7.3 跟练:本机网络长什么样
步骤 1 — 网卡与 IP
ip -br addr show
hostname -I
你应该看到:类似 eth0 / lo;lo 是 127.0.0.1(本机回环);WSL 还有 eth0 的局域网 IP。
读懂:
| 接口 | 含义 |
|---|---|
lo | 本机访问本机,永远 127.0.0.1 |
eth0 / wlan0 | 真实或虚拟网卡 |
步骤 2 — 默认路由(包往哪走)
ip route | head -5
步骤 3 — DNS 配置
cat /etc/resolv.conf
getent hosts github.com
你应该看到:nameserver 一行或多行;getent 解析出 GitHub 的 IP。为什么 Could not resolve host 先查这里和本机 DNS。
步骤 4 — 连通性( icmp,可能被禁)
ping -c 3 114.114.114.114
ping -c 2 github.com
能 ping 通不代表 HTTP 通;HTTP 还要查端口和进程。
7.4 跟练:谁在用哪个端口(与 ch05 联动)
步骤 1 — 列出 TCP 监听
ss -tlnp | head -25
读懂表头:Local Address:Port → 0.0.0.0:22 表示所有网卡监听 22;127.0.0.1:xxxx 表示只本机可连。
步骤 2 — 查 22 和 8080
ss -tlnp | grep ':22'
ss -tlnp | grep ':8080' || echo "8080 暂无监听(ch14 前正常)"
步骤 3 — 若 ch05 heartbeat 在跑,不会有 8080;若有其它实验服务
sudo ss -tlnp | grep LISTEN
加 sudo often 能看到进程名(users:(("nginx",pid=...)))。
排查口诀:
curl Connection refused
→ ss -tlnp 看端口有没有 LISTEN
→ 没有 → systemctl start 或程序没起来(ch05)
→ 有 → 地址是否 127.0.0.1 vs 0.0.0.0、防火墙(ufw)
7.5 curl 基础:HTTP 的「命令行浏览器」
步骤 1 — 最简单 GET
curl -s https://httpbin.org/get
你应该看到:一大段 JSON,含 "url": "https://httpbin.org/get"。
步骤 2 — 只看 HTTP 状态码
curl -s -o /dev/null -w "HTTP %{http_code}\n" https://httpbin.org/get
期望:HTTP 200
读懂参数:
| 参数 | 作用 |
|---|---|
-s | 静默,少进度条 |
-o /dev/null | 响应体丢弃 |
-w "%{http_code}" | 只打印状态码 |
步骤 3 — verbose:看请求/响应头(必会)
curl -v https://httpbin.org/get 2>&1 | head -35
你应该看到(顺序大致如下):
* Connected to httpbin.org ...
> GET /get HTTP/1.1
> Host: httpbin.org
...
< HTTP/1.1 200 OK
< Content-Type: application/json
...
{ "args": {}, ... }
为什么 行以 > 开头是你发出去的;< 是服务器回来的。排 API 问题 80% 看状态码和 Content-Type。
7.6 跟练:模拟商城 API — POST JSON
shop_db 商品字段 price 是整数分(go-database)。下面 POST 与 gin-web 风格一致:
curl -s -X POST https://httpbin.org/post \
-H "Content-Type: application/json" \
-H "Accept: application/json" \