Skip to content

GetField 🎯

查询指定 IP 的单个字段,返回纯文本字符串。

🚀 单字段查询

当你只需要一个字段(如 country_codeasn),GetField 比拉取完整 IPInfo 更轻量。客户端会先校验字段名是否在白名单(validFields),非法字段不发请求直接报错。

签名

go
func (c *Client) GetField(ctx context.Context, ip, field string) (string, error)

端点

GET https://ipapi.co/{ip}/{field}/

参数

参数类型说明
ctxcontext.Context超时/取消
ipstringIPv4/IPv6
fieldstring字段名,见下表

返回

  • string:字段值(纯文本)
  • error

💡 注意:不校验 IP 格式

GetField 只校验 field 是否合法(查 validFields),ValidateIP。IP 格式错误由服务端返回。这是有意为之——某些字段查询对 IP 容错性更高。

合法字段(28 个)

ip network version city region region_code country country_name country_code country_code_iso3 country_capital country_tld continent_code in_eu postal latitude longitude latlong timezone utc_offset languages country_calling_code currency currency_name country_area country_population asn org hostname

按类别速查:

类别常用字段
🌐 网络标识ip network version asn org hostname
📍 地理位置city region region_code postal latitude longitude latlong
🏳 国家/地区country country_name country_code country_code_iso3 country_capital country_tld continent_code in_eu
🕐 时区timezone utc_offset
💱 货币currency currency_name country_calling_code
📊 其它languages country_area country_population

详见 字段总览

示例

go
country, _ := client.GetField(ctx, "8.8.8.8", "country_code")
fmt.Println(country) // US

asn, _ := client.GetField(ctx, "8.8.8.8", "asn")
fmt.Println(asn) // AS15169

内部流程

🎨 一图抵千言

GetField 的校验顺序与 GetIPInfo 不同:先查 validFields 白名单,校验 IP 格式。返回值是 string,无解码步骤。

下面这张时序图展示 GetField 在运行期与 doRequest、服务端、TrimSpace 之间的交互顺序与返回路径,补充上图静态调用链所不能体现的"时序与责任边界"视角。

下面这张决策树聚焦 field 合法性分支与各类返回/错误落点,从"输入校验"视角收束上文,便于快速判断"为什么没发请求"或"为什么拿到 error"。

🔍 为什么不校验 IP?

GetIPInfoValidateIP,而 GetField 只校验 field。这是有意设计:某些字段查询(如 ip 本身、asn)对 IP 容错性更高,把 IP 合法性判断交给服务端,避免客户端过度拦截。红底节点即客户端侧的唯一守卫——validFields 白名单。

错误

错误条件
ErrInvalidFieldfield 不在白名单(客户端校验,不发请求
ErrReservedIP保留地址
ErrRateLimited429

完整 vs 单字段

💡 配额省钱小窍门

需要 ≥3 个字段时,用 GetIPInfo 一次拿全量更划算——一次请求消耗一份配额。逐个 GetField 会按字段数累计请求。详见 字段概念

需要字段数推荐方法请求数说明
1 个GetField1最省,单字段直返
2 个GetField ×2 或 GetIPInfo2 / 1视配额预算权衡
≥3 个GetIPInfo1一次拿全量,最省配额

下一步

基于 MIT 许可证发布