This repository has been archived by the owner on Jan 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
addr.go
113 lines (86 loc) · 2.35 KB
/
addr.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
package main
import (
"encoding/json"
"log"
"net/http"
expand "github.com/openvenues/gopostal/expand"
parser "github.com/openvenues/gopostal/parser"
)
type Input struct {
Address string `json:address`
}
func jsonErrorMessage(msg string) []byte {
r := make(map[string]string)
r["error"] = msg
j, _ := json.Marshal(r)
return j
}
func healthHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodGet:
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
return
default:
http.Error(w, "405 method not allowed", 405)
return
}
}
func expandHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
w.Header().Set("Content-Type", "application/json")
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, string(jsonErrorMessage("Content-Type must be application/json")), 400)
return
}
var input Input
err := json.NewDecoder(r.Body).Decode(&input)
if err != nil {
http.Error(w, string(jsonErrorMessage("error decoding request")), 500)
return
}
w.WriteHeader(http.StatusOK)
expansions := expand.ExpandAddress(input.Address)
expansionsJson, _ := json.Marshal(expansions)
w.Write(expansionsJson)
return
default:
http.Error(w, "405 method not allowed", 405)
return
}
}
func parseHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case http.MethodPost:
w.Header().Set("Content-Type", "application/json")
if r.Header.Get("Content-Type") != "application/json" {
http.Error(w, string(jsonErrorMessage("Content-Type must be application/json")), 400)
return
}
var input Input
err := json.NewDecoder(r.Body).Decode(&input)
if err != nil {
http.Error(w, string(jsonErrorMessage("error decoding request")), 500)
return
}
w.WriteHeader(http.StatusOK)
parsed := make(map[string]string)
components := parser.ParseAddress(input.Address)
for _, component := range components {
parsed[component.Label] = component.Value
}
parsedJson, _ := json.Marshal(parsed)
w.Write(parsedJson)
return
default:
http.Error(w, "405 method not allowed", 405)
return
}
}
func main() {
http.HandleFunc("/api/v1/expand", expandHandler)
http.HandleFunc("/api/v1/parse", parseHandler)
http.HandleFunc("/healthz", healthHandler)
log.Fatal(http.ListenAndServe(":8123", nil))
}