From a12c8550cd7c4656fc67092d58f4ce12cb19ecfe Mon Sep 17 00:00:00 2001 From: aaron Date: Thu, 29 Aug 2024 23:08:39 +0200 Subject: [PATCH] add station_locations.go which displays a list of all stations to print on a map --- publibike/station_locations.go | 47 ++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 publibike/station_locations.go diff --git a/publibike/station_locations.go b/publibike/station_locations.go new file mode 100644 index 0000000..942acdc --- /dev/null +++ b/publibike/station_locations.go @@ -0,0 +1,47 @@ +package publibike + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" +) + +// StationLoc struct to store station data +type StationLoc struct { + Id int `json:"id"` + Latitude float64 `json:"latitude"` + Longitude float64 `json:"longitude"` + State State `json:"state"` +} + +// State struct to store station state +type State struct { + Id int `json:"id"` + Name string `json:"name"` +} + +// GetAllStationLocations fetches data from /public/stations +// Use case: display the location of the stations on a map and whether or not bikes are available. +func GetAllStationLocations() ([]StationLoc, error) { + // Get the public data from the api endpoint + res, err := http.Get("https://api.publibike.ch/v1/public/stations") + if err != nil { + return nil, fmt.Errorf("failed to get stations from api: %w", err) + } + defer res.Body.Close() + + // Parse the JSON body + body, err := ioutil.ReadAll(res.Body) + if err != nil { + return nil, fmt.Errorf("failed to read response body: %w", err) + } + + var stationlocs []StationLoc + err = json.Unmarshal(body, &stationlocs) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal station: %w", err) + } + + return station, nil +}