-
Notifications
You must be signed in to change notification settings - Fork 0
/
phonecode.go
83 lines (73 loc) · 1.56 KB
/
phonecode.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package phonecode
import (
"encoding/csv"
"io"
"log"
"os"
"bufio"
"github.com/pkg/errors"
)
// New instance of Reader
func New(args ...string) (*Reader, error) {
var (
file = dataFile
reader = new(Reader)
err error
)
if len(args) > 0 {
file = args[0]
}
reader.file = file
reader.records = make(map[string]*Record)
err = reader.load()
return reader, err
}
// Define some constants in package
const (
dataFile = "data/phonecode.csv"
)
type (
// Record is a struct that represent a record in csv file
Record struct {
// Calling code of a country
Code string `json:"code"`
// Country code
CountryCode string `json:"country_code"`
}
// Reader is a struct wraps methods to lookup calling code
Reader struct {
file string
records map[string]*Record
}
)
// Load csv data
func (reader *Reader) load() error {
var (
csvFile, err = os.Open(reader.file)
r = csv.NewReader(bufio.NewReader(csvFile))
)
if err != nil {
return errors.New("Error when loading reader with message: " + err.Error())
}
for {
line, err := r.Read()
if err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
reader.records[line[1]] = &Record{
Code: line[0],
CountryCode: line[1],
}
}
return nil
}
// LookupPhoneCode is a method to lookup country with given phone code
func (reader *Reader) LookupPhoneCode(countryCode string) *Record {
return reader.records[countryCode]
}
// GetRecords is a method to get all records from reader
func (reader *Reader) GetRecords() map[string]*Record {
return reader.records
}