diff --git a/geolite2/fly.toml b/geolite2/fly.toml index 37dec38..bfd87f4 100644 --- a/geolite2/fly.toml +++ b/geolite2/fly.toml @@ -16,7 +16,7 @@ primary_region = 'iad' [http_service] internal_port = 3000 force_https = true - auto_stop_machines = 'stop' + auto_stop_machines = 'off' auto_start_machines = true min_machines_running = 0 processes = ['app'] diff --git a/geolite2/main.go b/geolite2/main.go index ff6391e..d8dec36 100644 --- a/geolite2/main.go +++ b/geolite2/main.go @@ -37,25 +37,29 @@ func main() { return c.SendString("Hello, World!") }) - app.Get("/:ip", func(c *fiber.Ctx) error { - queryIp := c.Params("ip") + app.Get("/me", func(c *fiber.Ctx) error { + ip := c.IPs()[0] - db, err := geoip2.Open("./data/GeoLite2-City.mmdb") + record, err := getCity(ip) if err != nil { - log.Fatal(err) - } - defer db.Close() - - // If you are using strings that may be invalid, check that ip is not nil - ip := net.ParseIP(queryIp) - if ip == nil { - return c.JSON(fiber.Map{ - "success": false, "message": "Please provide a valid ip", + c.JSON(fiber.Map{ + "success": false, + "message": err.Error(), }) } - record, err := db.City(ip) + + return c.JSON(record) + }) + + app.Get("/:ip", func(c *fiber.Ctx) error { + queryIp := c.Params("ip") + + record, err := getCity(queryIp) if err != nil { - log.Fatal(err) + c.JSON(fiber.Map{ + "success": false, + "message": err.Error(), + }) } return c.JSON(record) @@ -91,6 +95,26 @@ func main() { c.Stop() } +func getCity(queryIp string) (*geoip2.City, error) { + db, err := geoip2.Open("./data/GeoLite2-City.mmdb") + if err != nil { + return nil, err + } + defer db.Close() + + // If you are using strings that may be invalid, check that ip is not nil + ip := net.ParseIP(queryIp) + if ip == nil { + return nil, errors.New("invalid ip") + } + + record, err := db.City(ip) + if err != nil { + return nil, errors.New("no data") + } + return record, nil +} + func downloadAndExtractDB() error { _, err := os.ReadDir("./data") if err != nil { diff --git a/redirect/fly.toml b/redirect/fly.toml index ee36d14..c419f7c 100644 --- a/redirect/fly.toml +++ b/redirect/fly.toml @@ -17,6 +17,6 @@ primary_region = 'dfw' processes = ['app'] [[vm]] - memory = '512' + memory = '256' cpu_kind = 'shared' cpus = 1