跳到主要内容

GeoIP 示例

Github StackBlitz

本项目演示了如何在 Go 应用程序中使用 Fiber 框架设置 GeoIP 查询服务。

先决条件

请确保您已安装以下各项

设置

  1. 克隆仓库

    git clone https://github.com/gofiber/recipes.git
    cd recipes/geoip
  2. 安装依赖

    go get
  3. 下载 GeoIP2 数据库文件并将其放置在项目目录中。

运行应用程序

  1. 启动应用程序

    go run main.go
  2. 通过 http://localhost:3000 访问应用程序。

示例

以下是带有 GeoIP 查询功能的 Fiber 应用程序的示例 main.go 文件

package main

import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/oschwald/geoip2-golang"
"net"
)

func main() {
app := fiber.New()

db, err := geoip2.Open("GeoLite2-City.mmdb")
if err != nil {
log.Fatal(err)
}
defer db.Close()

app.Get("/geoip/:ip", func(c *fiber.Ctx) error {
ip := c.Params("ip")
parsedIP := net.ParseIP(ip)
record, err := db.City(parsedIP)
if err != nil {
return c.Status(500).SendString(err.Error())
}
return c.JSON(record)
})

log.Fatal(app.Listen(":3000"))
}

参考资料