-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
359 lines (331 loc) · 8.34 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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
package main
import (
"database/sql"
"log"
"strconv"
"strings"
"github.com/gin-gonic/gin"
_ "github.com/jackc/pgx/v4/stdlib"
)
type Rental struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Type string `json:"type"`
Make string `json:"make"`
Model string `json:"model"`
Year int `json:"year"`
Length float64 `json:"length"`
Sleeps int `json:"sleeps"`
PrimaryImageURL string `json:"primary_image_url"`
Price struct {
Day float64 `json:"day"`
} `json:"price_per_day"`
Location struct {
City string `json:"city"`
State string `json:"state"`
Zip string `json:"zip"`
Country string `json:"country"`
Lat float64 `json:"lat"`
Lng float64 `json:"lng"`
} `json:"location"`
User struct {
ID int `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
} `json:"user"`
}
func getRental(c *gin.Context, db *sql.DB) {
// Read the single rental from the database
rentalID := c.Param("id")
var rental Rental
query := `SELECT
r.id,
r.name,
r.description,
r.type,
r.vehicle_make,
r.vehicle_model,
r.vehicle_year,
r.vehicle_length,
r.sleeps,
r.primary_image_url,
r.price_per_day,
r.home_city,
r.home_state,
r.home_zip,
r.home_country,
r.lat,
r.lng,
u.id as user_id,
u.first_name as user_first_name,
u.last_name as user_last_name
FROM rentals r
JOIN users u
ON r.user_id = u.id
WHERE r.id = $1`
row := db.QueryRow(query, rentalID)
err := row.Scan(
&rental.ID,
&rental.Name,
&rental.Description,
&rental.Type,
&rental.Make,
&rental.Model,
&rental.Year,
&rental.Length,
&rental.Sleeps,
&rental.PrimaryImageURL,
&rental.Price.Day,
&rental.Location.City,
&rental.Location.State,
&rental.Location.Zip,
&rental.Location.Country,
&rental.Location.Lat,
&rental.Location.Lng,
&rental.User.ID,
&rental.User.FirstName,
&rental.User.LastName,
)
if err != nil {
if err == sql.ErrNoRows {
c.JSON(400, gin.H{"error": "Not Found"})
} else {
log.Println(err)
c.JSON(500, gin.H{"error": "Internal Server Error"})
}
return
}
c.JSON(200, rental)
}
func getRentals(c *gin.Context, db *sql.DB) {
// Get the list of IDs from the query parameter
ids := c.Query("ids")
sort := c.Query("sort")
priceMin := c.Query("price_min")
priceMax := c.Query("price_max")
near := c.Query("near")
offset := c.DefaultQuery("offset", "0")
limit := c.DefaultQuery("limit", "10")
var query string
var values []interface{}
query = `SELECT
r.id,
r.name,
r.description,
r.type,
r.vehicle_make,
r.vehicle_model,
r.vehicle_year,
r.vehicle_length,
r.sleeps,
r.primary_image_url,
r.price_per_day,
r.home_city,
r.home_state,
r.home_zip,
r.home_country,
r.lat,
r.lng,
u.id as user_id,
u.first_name as user_first_name,
u.last_name as user_last_name
FROM rentals r
JOIN users u
ON r.user_id = u.id
WHERE 1=1`
if ids != "" {
// Split the IDs into a slice
idSlice := strings.Split(ids, ",")
// Construct the placeholders for the parameterized query
placeholders := make([]string, len(idSlice))
values = make([]interface{}, len(idSlice))
for i, id := range idSlice {
placeholders[i] = "$" + strconv.Itoa(i+1)
values[i] = id
}
// Construct the SQL query with the parameterized query
query = query + " AND r.id IN (" + strings.Join(placeholders, ",") + ") "
}
if priceMin != "" {
// Add the price_min filter to the query
priceMinValue, err := strconv.ParseFloat(priceMin, 64)
if err != nil {
// Handle the error
c.JSON(400, gin.H{"error": "Invalid price_min value"})
return
}
query += " AND r.price_per_day >= $" + strconv.Itoa(len(values)+1)
values = append(values, priceMinValue)
}
if priceMax != "" {
// Add the price_max filter to the query
priceMaxValue, err := strconv.ParseFloat(priceMax, 64)
if err != nil {
// Handle the error
c.JSON(400, gin.H{"error": "Invalid price_max value"})
return
}
query += " AND r.price_per_day <= $" + strconv.Itoa(len(values)+1)
values = append(values, priceMaxValue)
}
if near != "" {
// Split the latLng into latitude and longitude
latLng := strings.Split(near, ",")
if len(latLng) != 2 {
// Handle the error
c.JSON(400, gin.H{"error": "Invalid near value"})
return
}
// Convert the latitude and longitude to float64
lat, err := strconv.ParseFloat(latLng[0], 64)
if err != nil {
// Handle the error
c.JSON(400, gin.H{"error": "Invalid latitude value"})
return
}
lng, err := strconv.ParseFloat(latLng[1], 64)
if err != nil {
// Handle the error
c.JSON(400, gin.H{"error": "Invalid longitude value"})
return
}
// Add the near filter to the query
query += " AND earth_box(ll_to_earth($" + strconv.Itoa(len(values)+1) + ", $" + strconv.Itoa(len(values)+2) + "), 100 * 1609.34) @> ll_to_earth(r.lat, r.lng)"
values = append(values, lat, lng)
}
if sort != "" {
// Add the sort parameter to the query
sortField := ""
switch sort {
case "price":
sortField = "r.price_per_day"
case "id":
sortField = "r.id"
case "name":
sortField = "r.name"
case "description":
sortField = "r.description"
case "type":
sortField = "r.type"
case "make":
sortField = "r.vehicle_make"
case "model":
sortField = "r.vehicle_model"
case "year":
sortField = "r.vehicle_year"
case "length":
sortField = "r.vehicle_length"
case "sleeps":
sortField = "r.sleeps"
case "primary_image_url":
sortField = "r.primary_image_url"
case "city":
sortField = "r.home_city"
case "state":
sortField = "r.home_state"
case "zip":
sortField = "r.home_zip"
case "country":
sortField = "r.home_country"
case "lat":
sortField = "r.lat"
case "lng":
sortField = "r.lng"
case "user_id":
sortField = "u.id"
case "user_first_name":
sortField = "u.first_name"
case "user_last_name":
sortField = "u.last_name"
default:
c.JSON(400, gin.H{"error": "Invalid sort parameter"})
return
}
query += " ORDER BY " + sortField
}
// Add the limit filter to the query
limitValue, err := strconv.Atoi(limit)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid limit value"})
return
}
query += " LIMIT $" + strconv.Itoa(len(values)+1)
values = append(values, limitValue)
// Add the offset filter to the query
offsetValue, err := strconv.Atoi(offset)
if err != nil {
c.JSON(400, gin.H{"error": "Invalid offset value"})
return
}
query += " OFFSET $" + strconv.Itoa(len(values)+1)
values = append(values, offsetValue)
// Execute the SQL query with the provided values
rows, err := db.Query(query, values...)
if err != nil {
// Handle the error
c.JSON(500, gin.H{"error": "Failed to retrieve rentals"})
return
}
defer rows.Close()
// Iterate through the result set and build the rental list
rentals := make([]Rental, 0)
for rows.Next() {
rental := Rental{}
err := rows.Scan(
&rental.ID,
&rental.Name,
&rental.Description,
&rental.Type,
&rental.Make,
&rental.Model,
&rental.Year,
&rental.Length,
&rental.Sleeps,
&rental.PrimaryImageURL,
&rental.Price.Day,
&rental.Location.City,
&rental.Location.State,
&rental.Location.Zip,
&rental.Location.Country,
&rental.Location.Lat,
&rental.Location.Lng,
&rental.User.ID,
&rental.User.FirstName,
&rental.User.LastName,
)
if err != nil {
// Handle the error
log.Println(err)
c.JSON(500, gin.H{"error": "Failed to retrieve rentals"})
return
}
rentals = append(rentals, rental)
}
// Return the filtered rentals as JSON response
c.JSON(200, rentals)
}
func main() {
// Connect to the PostgreSQL database
db, err := sql.Open("pgx", "postgres://root:root@postgres:5432/testingwithrentals")
if err != nil {
log.Println("Failed to connect to database.")
log.Fatal("Failed to connect to the database:", err)
}
log.Println("Connected to database.")
defer db.Close()
// Initialize the gin engine
router := gin.Default()
// Define the routes and handlers
router.GET("/rentals/:id", func(c *gin.Context) {
getRental(c, db)
})
router.GET("/rentals", func(c *gin.Context) {
getRentals(c, db)
})
// Run the application
err = router.Run(":8080")
if err != nil {
log.Fatal("Failed to start the server:", err)
}
}