-
Notifications
You must be signed in to change notification settings - Fork 5
/
main.go
148 lines (120 loc) · 2.78 KB
/
main.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
package main
import (
"bytes"
"crypto/md5"
"encoding/csv"
"encoding/gob"
"encoding/hex"
"encoding/json"
"flag"
"io"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/corenzan/bbdb/web"
"golang.org/x/text/language"
"golang.org/x/text/search"
)
type dataRecord struct {
Name string `json:"name"`
Code string `json:"code"`
ISPB string `json:"ispb"`
}
var (
numericExpr = regexp.MustCompile(`^[0-9]+$`)
boolExpr = regexp.MustCompile(`^(y|yes|t|true|1)$`)
)
func loadAndHashData(path string) ([]*dataRecord, string) {
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
reader := csv.NewReader(file)
// Skip headers
if _, err = reader.Read(); err != nil {
panic(err)
}
var records []*dataRecord
for {
data, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
r := &dataRecord{
ISPB: data[0],
Name: strings.TrimSpace(data[5]),
}
if numericExpr.MatchString(data[2]) {
r.Code = data[2]
}
records = append(records, r)
}
hasher := md5.New()
var b bytes.Buffer
gob.NewEncoder(&b).Encode(records)
hasher.Write(b.Bytes())
return records, hex.EncodeToString(hasher.Sum(nil))
}
func apiHandler(database []*dataRecord, matcher *search.Matcher) web.Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
next.ServeHTTP(w, r)
return
}
if err := r.ParseForm(); err != nil {
log.Print("ParseForm():", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("Access-Control-Allow-Origin", "*")
results := []*dataRecord{}
query := r.FormValue("q")
if query == "" {
results = database
} else {
for _, record := range database {
match := matcher.CompileString(query)
if i, _ := match.IndexString(record.Code + " " + record.Name); i > -1 {
results = append(results, record)
}
}
}
if boolExpr.MatchString(r.FormValue("compe")) {
tmp := results[:0]
for _, record := range results {
if record.Code != "" {
tmp = append(tmp, record)
}
}
results = tmp
}
json.NewEncoder(w).Encode(results)
})
}
}
func main() {
var (
addr string
src string
)
flag.StringVar(&addr, "addr", ":8080", "Address the server will listen on")
flag.StringVar(&src, "src", "data.csv", "Path to CSV data source")
flag.Parse()
database, etag := loadAndHashData(src)
matcher := search.New(language.BrazilianPortuguese, search.Loose)
w := web.New()
w.Use(web.LoggingHandler())
w.Use(web.CachingHandler(time.Hour*24*365, etag))
w.Use(web.RemoteAddrHandler())
w.Use(apiHandler(database, matcher))
w.Listen(addr)
}