-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvehicles.go
84 lines (60 loc) · 1.51 KB
/
vehicles.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
package totoro
import (
"io/ioutil"
"encoding/json"
"net/http"
"net/url"
)
//Vehicle data type
type Vehicle struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
VehicleClass string `json:"vehicle_class"`
Length string `json:"length"`
Pilot string `json:"pilot"`
Films string `json:"films"`
URL string `json:"url"`
}
//GetVehicles gets all the vehicles
func GetVehicles(query ...map[string]string) ([]Vehicle, error) {
params := url.Values{}
if len(query) > 0 {
for key, value := range query[0] {
params.Set(key, value)
}
}
var vehicles []Vehicle
vehicleRes, err := http.Get(apiURL + "/vehicles?" + params.Encode())
if err != nil {
return vehicles, err
}
defer vehicleRes.Body.Close()
vehiclesBytes, byteErrors := ioutil.ReadAll(vehicleRes.Body)
if byteErrors != nil {
return vehicles, byteErrors
}
jsonError := json.Unmarshal(vehiclesBytes, &vehicles)
if jsonError != nil {
return vehicles, jsonError
}
return vehicles, nil
}
//GetVehiclesByID gets a vehicle by id
func GetVehiclesByID(id string) (Vehicle, error){
vehicleRes, err := http.Get(apiURL + "/vehicles/" + id)
if err != nil {
return Vehicle{}, err
}
defer vehicleRes.Body.Close()
vehicleBytes, byteError := ioutil.ReadAll(vehicleRes.Body)
if byteError != nil {
return Vehicle{}, byteError
}
var vehicle Vehicle
jsonError := json.Unmarshal(vehicleBytes, &vehicle)
if jsonError != nil {
return Vehicle{}, jsonError
}
return vehicle, nil
}