Skip to main content

GeoIP Example

Github StackBlitz

This project demonstrates how to set up a GeoIP lookup service in a Go application using the Fiber framework.

Prerequisites

Ensure you have the following installed:

Setup

  1. Clone the repository:

    git clone https://github.com/gofiber/recipes.git
    cd recipes/geoip
  2. Install dependencies:

    go get
  3. Download the GeoIP2 database file and place it in the project directory.

Running the Application

  1. Start the application:

    go run main.go
  2. Access the application at http://localhost:3000.

Example

Here is an example main.go file for the Fiber application with GeoIP lookup:

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"))
}

References