Files
telemt-api/internal/geoip/config_open.go
T
Denozordec d7a63f0da3
Publish telemt-api gateway Docker image / test (push) Failing after 17s
Publish telemt-api gateway Docker image / build-and-push (push) Has been skipped
Add GeoIP support for unique IP aggregation
- Introduced GeoIP configuration options in config.example.yaml to enable geolocation lookups for the /api/agg/unique-ips endpoint.
- Updated the aggregate handler to include optional GeoIP data in responses, enriching unique IP information with country and city details, as well as ASN data if available.
- Enhanced documentation in AGGREGATE.md and README.md to reflect the new GeoIP functionality and its usage.
- Added a dependency on the geoip2-golang library in go.mod for GeoIP lookups.
- Modified tests to accommodate the new GeoIP integration in the aggregate handler.
2026-03-30 01:47:08 +07:00

71 lines
1.9 KiB
Go

package geoip
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"strings"
"time"
"github.com/telemt/telemt-api/internal/config"
)
// FromConfig ensures MMDB files exist (optional download) and opens readers. Returns nil if geoip disabled.
func FromConfig(cfg *config.GeoIPConfig, httpClient *http.Client, log *slog.Logger) (*Service, error) {
if cfg == nil || !cfg.Enabled {
return nil, nil
}
cityPath := strings.TrimSpace(cfg.DatabasePath)
asnPath := strings.TrimSpace(cfg.AsnDatabasePath)
if cityPath == "" && asnPath == "" {
return nil, errors.New("geoip.enabled requires at least one of geoip.database_path or geoip.asn_database_path")
}
if httpClient == nil {
httpClient = http.DefaultClient
}
if cityPath != "" {
if _, err := os.Stat(cityPath); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if cfg.DownloadURL == "" {
return nil, fmt.Errorf("geoip city database %q missing and geoip.download_url is empty", cityPath)
}
if log != nil {
log.Info("geoip downloading city database", "url", cfg.DownloadURL, "path", cityPath)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
if err := DownloadMMDB(ctx, httpClient, cfg.DownloadURL, cityPath); err != nil {
return nil, err
}
}
}
if asnPath != "" {
if _, err := os.Stat(asnPath); err != nil {
if !os.IsNotExist(err) {
return nil, err
}
if cfg.AsnDownloadURL == "" {
return nil, fmt.Errorf("geoip asn database %q missing and geoip.asn_download_url is empty", asnPath)
}
if log != nil {
log.Info("geoip downloading asn database", "url", cfg.AsnDownloadURL, "path", asnPath)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Minute)
defer cancel()
if err := DownloadMMDB(ctx, httpClient, cfg.AsnDownloadURL, asnPath); err != nil {
return nil, err
}
}
}
return OpenDatabases(cityPath, asnPath)
}