golang访问REST Countries API数据插件库go-restcountries的使用
Golang访问REST Countries API数据插件库go-restcountries的使用
简介
go-restcountries是一个用于访问Countrylayer REST Countries API(原restcountries.eu)的Golang封装库,支持最新的v2版本API。
注意:原restcountries.eu提供的免费API现已迁移至countrylayer.com,需要API密钥才能使用。go-restcountries v2完全支持Countrylayer API。
支持的API方法(v2 API所有方法都支持)
- All - 获取所有国家
- Name - 按国家名称搜索(支持精确或模糊匹配)
- Capital - 按首都城市搜索(模糊匹配)
- Currency - 按ISO 4217货币代码搜索(精确匹配)
- Language - 按ISO 639-1语言代码搜索(精确匹配)
- Region - 按地区搜索:非洲、美洲、亚洲、欧洲、大洋洲(精确匹配)
- RegionalBloc - 按区域集团搜索:EU、EFTA、CARICOM、PA等(精确匹配)
- CallingCode - 按电话区号搜索(精确匹配)
- Code/List of Codes(方法名为Codes) - 按ISO 3166-1 2字母或3字母国家代码搜索(精确匹配)
使用示例
获取所有国家
package main
import (
"fmt"
"github.com/chriscross0/go-restcountries/v2"
)
func main(){
client := restcountries.New("YOUR_API_KEY")
client.SetApiRoot("http://api.countrylayer.com/v2") // 免费计划需要使用http而非https
// 获取所有国家(所有字段)
countries, err := client.All(restcountries.AllOptions{})
if err != nil {
fmt.Println(err)
} else {
fmt.Println("Total countries: ", len(countries)) // 250
fmt.Println("First country name: ", countries[0].Name) // Afghanistan
fmt.Println("First country capital: ", countries[0].Capital) // Kabul
}
}
按国家名称搜索 - 模糊匹配
countries, err := client.Name(restcountries.NameOptions{
Name: "United States",
})
fmt.Println("Total countries: ", len(countries)) // 2
fmt.Println("First country name: ", countries[0].Name) // United States Minor Outlying Islands
fmt.Println("Second country name: ", countries[1].Name) // United States of America
按国家名称搜索 - 精确匹配
countries, err := client.Name(restcountries.NameOptions{
Name: "United States of America",
FullText: true, // true表示精确匹配
})
fmt.Println("Total countries: ", len(countries)) // 1
fmt.Println("First country name: ", countries[0].Name) // United States of America
按首都城市搜索 - 模糊匹配(单个国家)
countries, err := client.Capital(restcountries.CapitalOptions{
Name: "London",
})
fmt.Println("Total countries: ", len(countries)) // 1
fmt.Println("First country name: ", countries[0].Name) // United Kingdom of Great Britain and Northern Ireland
按货币代码搜索 - 精确匹配(单个国家)
countries, err := client.Currency(restcountries.CurrencyOptions{
Currency: "IDR",
})
fmt.Println("Total countries: ", len(countries)) // 1
fmt.Println("First country name: ", countries[0].Name) // Indonesia
按语言代码搜索 - 精确匹配(多个国家)
countries, err := client.Language(restcountries.LanguageOptions{
Language: "FF",
})
fmt.Println("Total countries: ", len(countries)) // 2
fmt.Println("First country name: ", countries[0].Name) // Burkina Faso
fmt.Println("Second country name: ", countries[1].Name) // Guinea
按地区搜索 - 精确匹配(多个国家)
countries, err := client.Region(restcountries.RegionOptions{
Region: "Oceania",
})
fmt.Println("Total countries: ", len(countries)) // 27
fmt.Println("First country name: ", countries[0].Name) // American Samoa
fmt.Println("Second country name: ", countries[1].Name) // Australia
按区域集团搜索 - 精确匹配(多个国家)
countries, err := client.RegionalBloc(restcountries.RegionalBlocOptions{
RegionalBloc: "PA",
})
fmt.Println("Total countries: ", len(countries)) // 4
fmt.Println("First country name: ", countries[0].Name) // Chile
fmt.Println("Second country name: ", countries[1].Name) // Colombia
按电话区号搜索 - 精确匹配(单个国家)
countries, err := client.CallingCode(restcountries.CallingCodeOptions{
CallingCode: "372",
})
fmt.Println("Total countries: ", len(countries)) // 1
fmt.Println("First country name: ", countries[0].Name) // Estonia
按国家代码搜索 - 精确匹配(单个国家)
countries, err := client.Codes(restcountries.CodesOptions{
Codes: []string{"CO"}, // 单个代码
})
fmt.Println("Total countries: ", len(countries)) // 1
fmt.Println("First country name: ", countries[0].Name) // Colombia
按国家代码搜索 - 精确匹配(多个国家)
countries, err := client.Codes(restcountries.CodesOptions{
Codes: []string{"CO", "GB"}, // 多个代码
})
fmt.Println("Total countries: ", len(countries)) // 2
fmt.Println("First country name: ", countries[0].Name) // Colombia
fmt.Println("Second country name: ", countries[1].Name) // United Kingdom of Great Britain and Northern Ireland
字段过滤
默认情况下,API会返回所有字段并填充到Country类型中。可以通过指定白名单字段来限制返回的字段。Fields
属性支持All()
、Name()
、Capital()
、Currency()
、Language()
、Region()
、RegionalBloc()
、CallingCode()
和Codes()
方法。
// 获取所有国家,只包含Name和Capital字段
countries, err := client.All(restcountries.AllOptions{
Fields: []string{"Name", "Capital"},
})
fmt.Println(countries[0].Name) // Afghanistan
fmt.Println(countries[0].Capital) // Kabul
fmt.Println(countries[0].Region) // 空,因为未请求此字段
配置
SetTimeout()
HTTP客户端的默认超时为0
(表示无超时)。可以使用SetTimeout()
覆盖默认超时,使用time.Duration
。
client := restcountries.New("YOUR_API_KEY")
client.SetTimeout(10 * time.Second) // 10秒
SetApiRoot()
默认API根URL为https://api.countrylayer.com/v2
。可以使用SetApiRoot()
覆盖根URL。如果使用免费计划,则需要将根URL覆盖为http而非https,因为免费计划不支持https。
client := restcountries.New("YOUR_API_KEY")
client.SetApiRoot("http://api.countrylayer.com/v2")
支持的字段
v2 restcountries API中的所有字段都受支持。以下是Country类型定义:
type Country struct {
Name string `json:"name"`
TopLevelDomain []string `json:"topLevelDomain"`
Alpha2Code string `json:"alpha2Code"`
Alpha3Code string `json:"alpha3Code"`
CallingCodes []string `json:"callingCodes"`
Capital string `json:"capital"`
AltSpellings []string `json:"altSpellings"`
Region string `json:"region"`
Subregion string `json:"subregion"`
Population int `json:"population"`
Latlng []float64 `json:"latlng"`
Demonym string `json:"demonym"`
Area float64 `json:"area"`
Gini float64 `json:"gini"`
Timezones []string `json:"timezones"`
Borders []string `json:"borders"`
NativeName string `json:"nativeName"`
NumericCode string `json:"numericCode"`
Currencies []struct {
Code string `json:"code"`
Name string `json:"name"`
Symbol string `json:"symbol"`
} `json:"currencies"`
Languages []struct {
Iso6391 string `json:"iso639_1"`
Iso6392 string `json:"iso639_2"`
Name string `json:"name"`
NativeName string `json:"nativeName"`
} `json:"languages"`
Translations struct {
De string `json:"de"`
Es string `json:"es"`
Fr string `json:"fr"`
Ja string `json:"ja"`
It string `json:"it"`
Br string `json:"br"`
Pt string `json:"pt"`
Nl string `json:"nl"`
Hr string `json:"hr"`
Fa string `json:"fa"`
} `json:"translations"`
Flag string `json:"flag"`
RegionalBlocs []struct {
Acronym string `json:"acronym"`
Name string `json:"name"`
OtherAcronyms []string `json:"otherAcronyms"`
OtherNames []string `json:"otherNames"`
} `json:"regionalBlocs"`
Cioc string `json:"cioc"`
}
更多关于golang访问REST Countries API数据插件库go-restcountries的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang访问REST Countries API数据插件库go-restcountries的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
使用go-restcountries访问REST Countries API
go-restcountries是一个Golang库,用于方便地访问REST Countries API数据。下面我将介绍如何使用这个库来获取国家信息。
安装
首先安装go-restcountries库:
go get github.com/henomis/restcountries-go
基本使用
1. 初始化客户端
package main
import (
"fmt"
"log"
"github.com/henomis/restcountries-go/restcountries"
)
func main() {
client := restcountries.NewClient()
2. 按国家名称查询
// 按国家全名查询
country, err := client.GetCountryByName("China")
if err != nil {
log.Fatal(err)
}
fmt.Printf("国家名称: %s\n", country[0].Name.Common)
fmt.Printf("首都: %s\n", country[0].Capital[0])
fmt.Printf("人口: %d\n", country[0].Population)
fmt.Printf("地区: %s\n", country[0].Region)
fmt.Printf("子地区: %s\n", country[0].Subregion)
3. 按国家代码查询
// 按alpha2/alpha3代码查询
countryByCode, err := client.GetCountryByCode("CN")
if err != nil {
log.Fatal(err)
}
fmt.Printf("国家代码查询结果: %s\n", countryByCode[0].Name.Common)
4. 按货币代码查询
// 按货币代码查询
countriesByCurrency, err := client.GetCountryByCurrency("CNY")
if err != nil {
log.Fatal(err)
}
fmt.Println("使用人民币的国家:")
for _, c := range countriesByCurrency {
fmt.Println(c.Name.Common)
}
5. 按语言代码查询
// 按语言代码查询
countriesByLanguage, err := client.GetCountryByLanguage("zh")
if err != nil {
log.Fatal(err)
}
fmt.Println("使用中文的国家/地区:")
for _, c := range countriesByLanguage {
fmt.Println(c.Name.Common)
}
6. 按地区查询
// 按地区查询
countriesByRegion, err := client.GetCountryByRegion("Asia")
if err != nil {
log.Fatal(err)
}
fmt.Println("亚洲国家:")
for _, c := range countriesByRegion {
fmt.Println(c.Name.Common)
}
7. 获取所有国家
// 获取所有国家
allCountries, err := client.GetAllCountries()
if err != nil {
log.Fatal(err)
}
fmt.Printf("总共有%d个国家\n", len(allCountries))
高级用法
过滤返回字段
// 只返回特定字段
filteredCountry, err := client.GetCountryByName("Japan", restcountries.WithFields([]string{"name", "capital", "population"}))
if err != nil {
log.Fatal(err)
}
fmt.Printf("日本人口: %d\n", filteredCountry[0].Population)
使用上下文
// 使用context
ctx := context.Background()
countryWithCtx, err := client.GetCountryByNameWithContext(ctx, "France")
if err != nil {
log.Fatal(err)
}
fmt.Printf("法国首都: %s\n", countryWithCtx[0].Capital[0])
完整示例
package main
import (
"fmt"
"log"
"github.com/henomis/restcountries-go/restcountries"
)
func main() {
client := restcountries.NewClient()
// 查询中国信息
china, err := client.GetCountryByName("China")
if err != nil {
log.Fatal(err)
}
fmt.Println("=== 中国信息 ===")
fmt.Printf("官方名称: %s\n", china[0].Name.Official)
fmt.Printf("首都: %s\n", china[0].Capital[0])
fmt.Printf("人口: %d\n", china[0].Population)
fmt.Printf("面积: %.2f 平方公里\n", china[0].Area)
fmt.Printf("时区: %v\n", china[0].Timezones)
fmt.Printf("顶级域名: %v\n", china[0].TLD)
fmt.Printf("货币: %v\n", china[0].Currencies)
fmt.Printf("语言: %v\n", china[0].Languages)
fmt.Printf("经纬度: %v\n", china[0].LatLng)
fmt.Printf("国旗: %s\n", china[0].Flags.PNG)
}
注意事项
- REST Countries API有请求频率限制,免费版大约每分钟100次请求
- 对于生产环境,建议添加适当的错误处理和重试机制
- 考虑缓存频繁访问的国家数据以减少API调用
- 某些字段可能是数组或对象,需要适当处理
go-restcountries库提供了对REST Countries API的完整封装,使用它可以方便地获取全球各国的各种信息,包括基本信息、货币、语言、时区等。