country-geo-locations/internal/csv_importer/csv_importer.go

82 lines
1.5 KiB
Go
Raw Normal View History

2024-11-26 13:35:54 +01:00
package csvimporter
2023-12-19 13:56:03 +01:00
import (
"encoding/csv"
"os"
"strconv"
2024-11-26 13:35:54 +01:00
"git.ar21.de/yolokube/country-geo-locations/internal/database"
"git.ar21.de/yolokube/country-geo-locations/pkg/geoloc"
2023-12-19 13:56:03 +01:00
)
2024-11-26 13:35:54 +01:00
func parseCSV(filePath string) ([]geoloc.IPInfo, error) {
file, fileErr := os.Open(filePath)
if fileErr != nil {
return nil, fileErr
2023-12-19 13:56:03 +01:00
}
defer file.Close()
reader := csv.NewReader(file)
2024-11-26 13:35:54 +01:00
var data []geoloc.IPInfo
2023-12-19 13:56:03 +01:00
for {
record, err := reader.Read()
if err != nil {
break
}
2024-11-26 13:35:54 +01:00
ipnumfrom, err := strconv.ParseUint(record[0], 10, 64)
2023-12-19 13:56:03 +01:00
if err != nil {
continue
}
2024-11-26 13:35:54 +01:00
ipnumto, err := strconv.ParseUint(record[1], 10, 64)
2023-12-19 13:56:03 +01:00
if err != nil {
continue
}
if record[2] == "-" {
record[2] = ""
}
if record[3] == "-" {
record[3] = ""
}
if record[4] == "-" {
record[4] = ""
}
if record[5] == "-" {
record[5] = ""
}
latitude, err := strconv.ParseFloat(record[6], 32)
if err != nil {
latitude = 0
}
longitude, err := strconv.ParseFloat(record[7], 32)
if err != nil {
longitude = 0
}
2024-11-26 13:35:54 +01:00
ipinfo := geoloc.IPInfo{
2023-12-19 13:56:03 +01:00
IPNumFrom: uint(ipnumfrom),
IPNumTo: uint(ipnumto),
Code: record[2],
Country: record[3],
State: record[4],
City: record[5],
Latitude: float32(latitude),
Longitude: float32(longitude),
}
data = append(data, ipinfo)
}
return data, nil
}
2024-11-26 13:35:54 +01:00
func ImportCSV(filePath string, db *database.Database) error {
2023-12-19 13:56:03 +01:00
ipinfos, err := parseCSV(filePath)
if err != nil {
return err
}
2024-11-26 13:35:54 +01:00
return db.Load(ipinfos)
2023-12-19 13:56:03 +01:00
}