-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
126 lines (101 loc) · 2.45 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
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"time"
"github.com/go-redis/redis/v8"
)
func main() {
fmt.Println("Starting the server...")
api := NewAPI()
http.HandleFunc("/health", healthCheck)
http.HandleFunc("/cache", api.Handler)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%s", os.Getenv("PORT")), nil))
}
func healthCheck(w http.ResponseWriter, r *http.Request) {
resp := HealthCheck{
Status: "OK",
Date: time.Now(),
}
err := json.NewEncoder(w).Encode(resp)
if err != nil {
fmt.Printf("error encoding response: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (a *API) Handler(w http.ResponseWriter, r *http.Request) {
q := r.URL.Query().Get("q")
data, cached, err := a.getData(r.Context(), q)
if err != nil {
fmt.Printf("error calling data source: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Printf("send a request for: %s\n", q)
resp := APIResponse{
Cache: cached,
Data: data,
}
err = json.NewEncoder(w).Encode(resp)
if err != nil {
fmt.Printf("error encoding response: %v\n", err)
w.WriteHeader(http.StatusInternalServerError)
return
}
}
func (a *API) getData(ctx context.Context, q string) ([]NominatimResponse, bool, error) {
val, err := a.cache.Get(ctx, q).Result()
if err == redis.Nil {
escapedQ := url.PathEscape(q)
address := fmt.Sprintf("https://nominatim.openstreetmap.org/search?q=%s&format=json", escapedQ)
resp, err := http.Get(address)
if err != nil {
return nil, false, err
}
data := make([]NominatimResponse, 0)
err = json.NewDecoder(resp.Body).Decode(&data)
if err != nil {
return nil, false, err
}
b, err := json.Marshal(data)
if err != nil {
return nil, false, err
}
err = a.cache.Set(ctx, q, bytes.NewBuffer(b).Bytes(), time.Second*15).Err()
if err != nil {
return nil, false, err
}
return data, false, nil
} else if err != nil {
fmt.Printf("error on redis: %v\n", err)
return nil, false, err
} else {
data := make([]NominatimResponse, 0)
err := json.Unmarshal(bytes.NewBufferString(val).Bytes(), &data)
if err != nil {
return nil, false, err
}
return data, true, nil
}
}
type API struct {
cache *redis.Client
}
func NewAPI() *API {
redisAddress := fmt.Sprintf("%s:6379", os.Getenv("REDIS_URL"))
rdb := redis.NewClient(&redis.Options{
Addr: redisAddress,
Password: "",
DB: 0,
})
return &API{
cache: rdb,
}
}