whatismyip/service/geo.go

74 lines
1.1 KiB
Go
Raw Normal View History

2021-11-10 19:06:12 +00:00
package service
import (
2025-01-02 19:13:41 +00:00
"context"
2021-11-10 19:06:12 +00:00
"log"
"net"
2025-01-02 19:13:41 +00:00
"sync"
2021-11-10 19:06:12 +00:00
"github.com/dcarrillo/whatismyip/models"
)
type Geo struct {
2025-01-02 19:13:41 +00:00
ctx context.Context
cancel context.CancelFunc
db *models.GeoDB
mu sync.RWMutex
2021-11-10 19:06:12 +00:00
}
2025-01-02 19:13:41 +00:00
func NewGeo(ctx context.Context, cityPath string, asnPath string) (*Geo, error) {
ctx, cancel := context.WithCancel(ctx)
db, err := models.Setup(cityPath, asnPath)
if err != nil {
cancel()
return nil, err
}
geo := &Geo{
ctx: ctx,
cancel: cancel,
db: db,
}
return geo, nil
}
func (g *Geo) LookUpCity(ip net.IP) *models.GeoRecord {
record, err := g.db.LookupCity(ip)
2021-11-10 19:06:12 +00:00
if err != nil {
2025-01-02 19:13:41 +00:00
log.Print(err)
2021-11-10 19:06:12 +00:00
return nil
}
return record
}
2025-01-02 19:13:41 +00:00
func (g *Geo) LookUpASN(ip net.IP) *models.ASNRecord {
record, err := g.db.LookupASN(ip)
2021-11-10 19:06:12 +00:00
if err != nil {
2025-01-02 19:13:41 +00:00
log.Print(err)
2021-11-10 19:06:12 +00:00
return nil
}
return record
}
2025-01-02 19:13:41 +00:00
func (g *Geo) Shutdown() {
g.cancel()
g.db.CloseDBs()
}
func (g *Geo) Reload() {
if err := g.ctx.Err(); err != nil {
log.Printf("Skipping reload, service is shutting down: %v", err)
return
}
g.mu.Lock()
defer g.mu.Unlock()
g.db.Reload()
log.Print("Geo database reloaded")
}