forked from johnlonganecker/libpostal-rest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
92 lines (73 loc) · 2 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
package main
import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/signal"
"time"
"github.com/gorilla/mux"
expand "github.com/openvenues/gopostal/expand"
parser "github.com/openvenues/gopostal/parser"
)
type Request struct {
Query string `json:"query"`
}
func main() {
host := os.Getenv("LISTEN_HOST")
if host == "" {
host = "0.0.0.0"
}
port := os.Getenv("LISTEN_PORT")
if port == "" {
port = "8080"
}
listenSpec := fmt.Sprintf("%s:%s", host, port)
certFile := os.Getenv("SSL_CERT_FILE")
keyFile := os.Getenv("SSL_KEY_FILE")
router := mux.NewRouter()
router.HandleFunc("/health", HealthHandler).Methods("GET")
router.HandleFunc("/expand", ExpandHandler).Methods("POST")
router.HandleFunc("/parser", ParserHandler).Methods("POST")
s := &http.Server{Addr: listenSpec, Handler: router}
go func() {
if certFile != "" && keyFile != "" {
fmt.Printf("listening on https://%s\n", listenSpec)
s.ListenAndServeTLS(certFile, keyFile)
} else {
fmt.Printf("listening on http://%s\n", listenSpec)
s.ListenAndServe()
}
}()
stop := make(chan os.Signal)
signal.Notify(stop, os.Interrupt)
<-stop
fmt.Println("\nShutting down the server...")
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
s.Shutdown(ctx)
fmt.Println("Server stopped")
}
func HealthHandler(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
w.Write([]byte("OK"))
}
func ExpandHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var req Request
q, _ := ioutil.ReadAll(r.Body)
json.Unmarshal(q, &req)
expansions := expand.ExpandAddress(req.Query)
expansionThing, _ := json.Marshal(expansions)
w.Write(expansionThing)
}
func ParserHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var req Request
q, _ := ioutil.ReadAll(r.Body)
json.Unmarshal(q, &req)
parsed := parser.ParseAddress(req.Query)
parseThing, _ := json.Marshal(parsed)
w.Write(parseThing)
}