Skip to content

Commit

Permalink
refactor: expose constructor from URL
Browse files Browse the repository at this point in the history
  • Loading branch information
danroc committed Oct 31, 2024
1 parent 71c12ab commit b0494d5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 16 deletions.
25 changes: 13 additions & 12 deletions pkg/database/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package database

import (
"encoding/csv"
"io"
"net"
"net/http"
"slices"
Expand All @@ -19,16 +20,6 @@ type Entry struct {
Data []string
}

// fetchCsv fetches a CSV file from the given URL and returns its records.
func fetchCsv(url string) ([][]string, error) {
resp, err := http.Get(url) // #nosec G107
if err != nil {
return nil, err
}
defer resp.Body.Close()
return csv.NewReader(resp.Body).ReadAll()
}

// sanatizeData trims the leading and trailing spaces from the given strings.
func sanatizeData(data []string) []string {
sanitized := make([]string, len(data))
Expand Down Expand Up @@ -78,9 +69,9 @@ type Database struct {
}

// NewDatabase creates a new database from the given URL.
func NewDatabase(url string) (*Database, error) {
func NewDatabase(reader io.Reader) (*Database, error) {
// Records are the raw data from the CSV file.
records, err := fetchCsv(url)
records, err := csv.NewReader(reader).ReadAll()
if err != nil {
return nil, err
}
Expand All @@ -98,6 +89,16 @@ func NewDatabase(url string) (*Database, error) {
return &Database{entries: entries}, nil
}

// NewDatabaseURL creates a new database from the given URL.
func NewDatabaseURL(url string) (*Database, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return NewDatabase(resp.Body)
}

// Find returns the data associated with the entry that contains the given IP.
// If the IP is not found, nil is returned.
func (db *Database) Find(ip net.IP) []string {
Expand Down
8 changes: 4 additions & 4 deletions pkg/database/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,22 +34,22 @@ type Resolver struct {

// NewResolver creates a new IP resolver.
func NewResolver() (*Resolver, error) {
countryDBv4, err := NewDatabase(countryIPv4URL)
countryDBv4, err := NewDatabaseURL(countryIPv4URL)
if err != nil {
return nil, err
}

countryDBv6, err := NewDatabase(countryIPv6URL)
countryDBv6, err := NewDatabaseURL(countryIPv6URL)
if err != nil {
return nil, err
}

asnDBv4, err := NewDatabase(asnIPv4URL)
asnDBv4, err := NewDatabaseURL(asnIPv4URL)
if err != nil {
return nil, err
}

asnDBv6, err := NewDatabase(asnIPv6URL)
asnDBv6, err := NewDatabaseURL(asnIPv6URL)
if err != nil {
return nil, err
}
Expand Down

0 comments on commit b0494d5

Please sign in to comment.