title | keywords | description | |||
---|---|---|---|---|---|
GeoIP |
|
Geolocation with GeoIP. |
This project demonstrates how to set up a GeoIP lookup service in a Go application using the Fiber framework.
Ensure you have the following installed:
- Golang
- Fiber package
- MaxMind GeoIP2 package
- GeoIP2 database file (e.g.,
GeoLite2-City.mmdb
)
-
Clone the repository:
git clone https://github.com/gofiber/recipes.git cd recipes/geoip
-
Install dependencies:
go get
-
Download the GeoIP2 database file and place it in the project directory.
-
Start the application:
go run main.go
-
Access the application at
http://localhost:3000
.
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"))
}