-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode.go
104 lines (80 loc) · 1.7 KB
/
code.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
package main
import (
"encoding/json"
"fmt"
"database/sql"
_ "github.com/mattn/go-sqlite3"
"net/http"
"sync"
)
var cache = make(map[string]*CodeResponse)
var lock sync.Mutex
type CodeResponse struct {
Kod string
Gmina string
Powiat string
Wojewodztwo string
WojewodztwoId int
}
func codeJsonHandler(rw http.ResponseWriter, req *http.Request) {
// fmt.Print("+")
code := req.FormValue("code")
r, err := getCode(code)
if err != nil {
fmt.Fprintln(rw, "error:", err)
return
}
m, err := json.Marshal(r)
if err != nil {
fmt.Fprintln(rw, "error:", err)
return
}
rw.Write(m)
}
func codeTextHandler(rw http.ResponseWriter, req *http.Request) {
code := req.FormValue("code")
r, err := getCode(code)
if err != nil {
fmt.Fprintln(rw, "error:", err)
return
}
fmt.Fprintf(rw, "%s;%s", r.Kod, r.Powiat)
}
func codeTextCacheHandler(rw http.ResponseWriter, req *http.Request) {
// fmt.Print("+")
code := req.FormValue("code")
lock.Lock()
defer lock.Unlock()
r, ok := cache[code]
if !ok {
r, err := getCode(code)
if err != nil {
fmt.Fprintln(rw, "error:", err)
return
}
cache[code] = r
}
fmt.Fprintf(rw, "%s;%s", r.Kod, r.Powiat)
}
var db *sql.DB
func init() {
var err error
db, err = sql.Open("sqlite3", "resources/teryt.sqlite")
if err != nil {
panic(err)
}
}
func getCode(code string) (*CodeResponse, error) {
q := fmt.Sprintf("SELECT kod, powiat, gmina, wojewodztwo FROM poczta where kod = '%s'", code)
rows, err := db.Query(q)
if err != nil {
return nil, err
}
defer rows.Close()
cr := &CodeResponse{}
for rows.Next() {
rows.Scan(&cr.Kod, &cr.Powiat, &cr.Gmina, &cr.WojewodztwoId)
return cr, nil
}
return nil, fmt.Errorf("No code %s", code)
}