首页
/ GeoIp 使用与技术文档

GeoIp 使用与技术文档

2024-12-20 19:10:18作者:史锋燃Gardner

1. 安装指南

GeoIp 是一个 Ruby Gem,可以通过以下命令安装:

gem install geo_ip

请注意,自版本 0.6.0 起,GeoIp 仅与 Ruby 1.9.3 或更高版本兼容。如果您需要与 Ruby 1.8.7 或 1.9.2 的兼容性,可以使用 0.5.0 版本。

Rails 集成

Bundler 支持(Rails 3.x 和 2.3.x)

在 Gemfile 中添加以下内容:

gem 'geo_ip'

然后创建一个初始化文件 config/initializers/geo_ip.rb(或您想要的任何名称):

GeoIp.api_key = 'YOUR_API_KEY'

预 Bundler 支持(Rails 2.3.x 或更早版本)

config/environment.rb 文件中添加以下内容:

config.gem 'geo_ip'

然后创建一个初始化文件 config/initializers/geo_ip.rb(或您想要的任何名称):

GeoIp.api_key = 'YOUR_API_KEY'

2. 项目的使用说明

在使用 GeoIp 之前,您需要设置 API 密钥。可以在任何地方进行设置,但必须在执行地理定位调用之前完成:

GeoIp.api_key = 'YOUR_API_KEY'

获取地理定位

要检索 IP 地址的地理定位信息,使用以下方法:

GeoIp.geolocation(ip_address)

示例

# 209.85.227.104 = google.be (美国)
GeoIp.geolocation('209.85.227.104')

返回结果:

{
  :status_code => "OK",
  :status_message => "",
  :ip => "209.85.227.104",
  :country_code => "US",
  :country_name => "UNITED STATES",
  :region_name => "CALIFORNIA",
  :city => "MONTEREY PARK",
  :zip_code => "91754",
  :latitude => "34.0505",
  :longitude => "-118.13"
}

只检索国家信息

如果只检索国家信息,可以排除城市细节。这样可以加快服务的响应速度,因为需要查询的数据更少。

GeoIp.geolocation('209.85.227.104', :precision => :country)

返回结果:

{
  :status_code => "OK",
  :status_message => "",
  :ip => "209.85.227.104",
  :country_code => "US",
  :country_name => "UNITED STATES"
}

时区信息

还可以选择检索可选的时区信息:

GeoIp.geolocation('209.85.227.104', :timezone => true)

返回结果:

{
  :status_code => "OK",
  :status_message => "",
  :ip => "209.85.227.104",
  :country_code => "US",
  :country_name => "UNITED STATES",
  :region_name => "CALIFORNIA",
  :city => "MONTEREY PARK",
  :zip_code => "91754",
  :latitude => "34.0505",
  :longitude => "-118.13",
  :timezone => "-08:00"
}

请注意,无法在检索时区信息时启用国家精度。

保留 / 私有 / 本地 IPs

传递保留、私有或本地 IPs(例如 127.0.0.1)将返回 - 作为所有位置数据:

GeoIp.geolocation('127.0.0.1')

返回结果:

{
  :status_code => "OK",
  :status_message => "",
  :ip => "127.0.0.1",
  :country_code => "-",
  :country_name => "-",
  :region_name => "-",
  :city => "-",
  :zip_code => "-",
  :latitude => "0",
  :longitude => "0"
}

超时

可以为所有请求设置超时。默认情况下,超时时间为一秒,但您可以将不同的值轻松设置。与设置 api_key 相同,您可以设置超时:

GeoIp.timeout = 5 # 将其设置为五秒

3. 项目API使用文档

GeoIp 项目主要通过其 Ruby Gem 接口提供 API。以下是主要方法的简要说明:

  • GeoIp.api_key: 设置用于身份验证的 API 密钥。
  • GeoIp.geolocation(ip_address, [options]): 根据 IP 地址检索地理定位信息。options 可以包括 :precision:timezone
  • GeoIp.timeout: 设置请求超时时间。

4. 项目安装方式

GeoIp 可以通过 Ruby Gem 安装。运行以下命令:

gem install geo_ip

对于 Rails 项目,您可以在 Gemfile 中添加 geo_ip,然后运行 bundle install。之后,在初始化文件中设置 API 密钥。

登录后查看全文
热门项目推荐