使用 Go 查询巴西 CPF
使用标准库中的 net/http 在 Go 中查询 CPF(巴西个人税号)。无外部依赖。
正在使用 Cursor、Lovable、v0 或其他 AI 工具? 复制标准查询的提示词,粘贴到您的 AI 助手中。
准备工作
- 在 app.cpfhub.io 免费创建账户。免费版包含 50 个积分,无需信用卡。
- 在 app.cpfhub.io/api-keys 复制您的 API 密钥。
- 将密钥保存在环境变量中,不要写进代码:
bash
export CPFHUB_API_KEY="sua_api_key"示例
Go
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"time"
)
type response struct {
Data *struct {
Name string `json:"name"`
BirthDate string `json:"birthDate"`
} `json:"data"`
// error is a string ("...") or an object ({"message": "..."})
Error json.RawMessage `json:"error"`
}
func main() {
cpf := "12345678909"
req, err := http.NewRequest(http.MethodGet, "https://api.cpfhub.io/cpf/"+cpf, nil)
if err != nil {
log.Fatal(err)
}
req.Header.Set("x-api-key", os.Getenv("CPFHUB_API_KEY"))
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()
var body response
if err := json.NewDecoder(resp.Body).Decode(&body); err != nil {
log.Fatal(err)
}
switch resp.StatusCode {
case http.StatusOK:
fmt.Println(body.Data.Name, body.Data.BirthDate)
case http.StatusNotFound:
fmt.Println("CPF not found (does not use a credit)")
case http.StatusTooManyRequests:
fmt.Println("Per-minute limit reached. Try again in", resp.Header.Get("Retry-After"), "s")
default:
log.Fatalf("Error %d: %s", resp.StatusCode, body.Error)
}
}保存为 main.go,然后使用 go run main.go 运行。
响应
查到 CPF(200,消耗 1 个积分):
JSON
{
"success": true,
"data": {
"cpf": "12345678909",
"name": "Fulano de Tal",
"nameUpper": "FULANO DE TAL",
"gender": "M",
"birthDate": "15/06/1990",
"day": 15,
"month": 6,
"year": 1990
}
}未查到 CPF(404,不消耗积分):
JSON
{
"success": false,
"data": null,
"error": { "message": "CPF não encontrado na base de dados" }
}CPF 12345678909 为虚构号码,仅用于示例。gender 可能为 null。error.message 的文本由 API 以葡萄牙语返回(意为“数据库中未找到该 CPF”)。
错误
| 状态码 | 含义 | 处理方式 |
|---|---|---|
404 | 数据库中没有该 CPF | 按“未找到”处理。不消耗积分。 |
400 / 422 | CPF 不是 11 位数字或校验位无效 | 修正输入。不消耗积分。 |
401 | 缺少 API 密钥或密钥无效 | 检查 CPFHUB_API_KEY 变量。 |
403 | 积分已用完或账户未激活 | 通过 GET /quota 查看余额,或在控制台充值。 |
429 | 超出每分钟请求限制 | 等待 Retry-After 响应头中的秒数,然后重试。 |
5xx | 临时故障 | 几秒后重试。 |
error 字段可能是文本("error": "..."),也可能是对象("error": { "message": "..." }),取决于状态码。上面的示例已处理这两种格式。完整列表见错误代码。