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 +}