-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
195 lines (168 loc) · 5.21 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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package main
import (
"context"
"embed"
_ "embed"
"fmt"
"github.com/fastly/compute-sdk-go/fsthttp"
"html/template"
"io"
"log"
"net/http"
"os"
"weather-app/foursquare"
"weather-app/location"
"weather-app/opencage"
"weather-app/templates"
"weather-app/weather"
)
//go:embed templates
var templateFS embed.FS
//go:generate npm run build
func main() {
fsthttp.ServeFunc(func(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
checkCors(w, r)
filterHTTPMethods(w, r)
handleHTTPOptions(w, r)
// STATIC FRONT PAGE ROUTE
if r.URL.Path == "/" {
serveFrontPage(ctx, w, r)
return
}
// TIMELINE ROUTE
if r.URL.Path == "/v2/timeline/" {
w.Header().Set("Cache-Control", "public, max-age=300")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var lat, long string
var err error
var resp *fsthttp.Response
lat = r.URL.Query().Get("lat")
long = r.URL.Query().Get("lon")
if lat != "" && long != "" {
resp, err = weather.GetWeatherRaw(ctx, lat, long)
if err != nil {
log.Println("Error: lat and long from backend: Failed getting weather data", err)
}
if err != nil {
log.Println("Error: failed to get opencage reverse geocoding", err)
}
} else {
//get details from embedded geo-reverse db
details, err := location.GetDetailsFromIp(r.RemoteAddr)
if err != nil {
log.Println(w, "Was not able to read from database: ", err)
}
lat = details.Lat
long = details.Long
resp, err = weather.GetWeatherRaw(ctx, lat, long)
if err != nil {
log.Println("Error: lat and long from browser. Failed getting weather data", err)
}
}
io.Copy(w, resp.Body)
return
}
//LOCATION NAME RESOLVER ROUTE
if r.URL.Path == "/v2/location-name-resolver/" {
w.Header().Set("Cache-Control", "public, max-age=300")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var lat string = r.URL.Query().Get("lat")
var long string = r.URL.Query().Get("lon")
resp, err := opencage.GetLocationMetaData(ctx, lat, long)
if err != nil {
fmt.Fprintf(w, "Error reading response body: %v\n", err)
}
io.Copy(w, resp.Body)
return
}
if r.URL.Path == "/v2/nearby/" {
w.Header().Set("Cache-Control", "public, max-age=300")
w.Header().Set("Content-Type", "application/json; charset=utf-8")
var lat string = r.URL.Query().Get("lat")
var long string = r.URL.Query().Get("lon")
var locType string = r.URL.Query().Get("type")
resp, err := foursquare.GetNearby(ctx, lat, long, locType)
if err != nil {
fmt.Fprintf(w, fmt.Sprintf("Error fetching nearby beaches: %v", err), http.StatusInternalServerError)
return
}
if resp.Body == nil {
fmt.Fprintf(w, "Received empty response body", http.StatusInternalServerError)
return
}
_, copyErr := io.Copy(w, resp.Body)
if copyErr != nil {
fmt.Fprintf(w, fmt.Sprintf("Error reading response body: %v", copyErr), http.StatusInternalServerError)
}
return
}
w.WriteHeader(fsthttp.StatusNotFound)
fmt.Fprintf(w, "The page you requested could not be found\n")
})
}
func checkCors(w fsthttp.ResponseWriter, r *fsthttp.Request) {
acceptedOrigins := map[string]bool{
"http://localhost:3000": true,
"https://weather-app-react-psi-one.vercel.app": true,
"https://www.localsonly.today": true,
"https://localsonly.today": true,
}
origin := r.Header.Get("Origin")
if acceptedOrigins[origin] {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
}
}
func filterHTTPMethods(w fsthttp.ResponseWriter, r *fsthttp.Request) {
if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" || r.Method == "DELETE" {
w.WriteHeader(fsthttp.StatusMethodNotAllowed)
fmt.Fprintf(w, "This method is not allowed\n")
return
}
}
func handleHTTPOptions(w fsthttp.ResponseWriter, r *fsthttp.Request) {
if r.Method == fsthttp.MethodOptions {
w.WriteHeader(fsthttp.StatusOK)
return
}
}
func serveFrontPage(ctx context.Context, w fsthttp.ResponseWriter, r *fsthttp.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
r.CacheOptions.TTL = 0
details, err := location.GetDetailsFromIp(r.RemoteAddr)
if err != nil {
fmt.Fprintf(w, "Was not able to read from databse: ", err)
}
weatherData, err := weather.GetWeather(ctx, details.Lat, details.Long)
if err != nil {
fmt.Fprintf(w, "Error reading weather data: ", err)
}
funcMap := template.FuncMap{
"GetDay": weather.GetDay,
}
tmpl, err := template.New("weather.html").Funcs(funcMap).ParseFS(templateFS, "templates/weather.html")
if err != nil {
fmt.Fprintf(w, "Error loading template:", err)
}
weatherTplData := templates.GetWeatherData(
os.Getenv("FASTLY_SERVICE_VERSION"),
details.City,
details.Country,
details.TimeZone,
details.Lat,
details.Long,
r.RemoteAddr,
weatherData.ResolvedAddress,
weatherData.CurrentConditions.Temperature,
weatherData.CurrentConditions.Conditions,
weatherData.Description,
weatherData.Address,
weatherData.CurrentConditions.Icon,
weatherData.Days,
)
err = tmpl.Execute(w, weatherTplData)
if err != nil {
fmt.Fprintf(w, "Error loading template:", err)
}
return
}