-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcountries.go
83 lines (67 loc) · 1.61 KB
/
countries.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 aptdata
import (
"encoding/csv"
"fmt"
"io"
"os"
"github.com/coreos/bbolt"
"github.com/pkg/errors"
"github.com/vmihailenco/msgpack"
)
//Country maps country codes to names
type Country struct {
Code string
Name string
}
//loadCountries processes countries.csv and loads a Country struct into
//the Countries bucket in the DB for every record
func loadCountries(db *bolt.DB, dataDir string) error {
countries, err := os.Open(fmt.Sprintf("%s/%s", dataDir, "countries.csv"))
if err != nil {
return err
}
defer countries.Close()
r := csv.NewReader(countries)
_, err = r.Read() // skip header
err = db.Update(func(tx *bolt.Tx) error {
_, err = tx.CreateBucketIfNotExists([]byte("Countries"))
if err != nil {
return err
}
b := tx.Bucket([]byte("Countries"))
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return errors.Wrap(err, "country read")
}
country := Country{record[1], record[2]}
m, err := msgpack.Marshal(&country)
if err != nil {
return errors.Wrap(err, "country marshal")
}
err = b.Put([]byte(record[1]), m)
if err != nil {
return errors.Wrap(err, "database put")
}
}
return nil
})
return err
}
//GetCountry returns a Country struct representing the given code
func (a *AptDB) GetCountry(ident string) (*Country, error) {
var country Country
err := a.boltDB.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Countries"))
v := b.Get([]byte(ident))
err := msgpack.Unmarshal(v, &country)
return err
})
if err != nil {
return &country, errors.Wrap(err, "get country")
}
return &country, nil
}