country-geo-locations/pkg/geoloc/csv_import.go

80 lines
1.3 KiB
Go
Raw Normal View History

2023-12-19 13:56:03 +01:00
package geoloc
import (
"encoding/csv"
"os"
"strconv"
)
func parseCSV(filePath string) ([]IPInfo, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
reader := csv.NewReader(file)
var data []IPInfo
for {
record, err := reader.Read()
if err != nil {
break
}
ipnumfrom, err := strconv.Atoi(record[0])
if err != nil {
continue
}
ipnumto, err := strconv.Atoi(record[1])
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
}
ipinfo := IPInfo{
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
}
func ImportCSV(filePath string) error {
ipinfos, err := parseCSV(filePath)
if err != nil {
return err
}
err = CreateDatabase(ipinfos)
return err
}