add station_locations.go which displays a list of all stations to print on a map
This commit is contained in:
47
publibike/station_locations.go
Normal file
47
publibike/station_locations.go
Normal file
@@ -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
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user