diff --git a/.gitignore b/.gitignore index adf8f72..e6cb87e 100644 --- a/.gitignore +++ b/.gitignore @@ -2,6 +2,9 @@ # If you prefer the allow list template instead of the deny list, see community template: # https://github.com/github/gitignore/blob/main/community/Golang/Go.AllowList.gitignore # +# VIM +.*.swp + # Binaries for programs and plugins *.exe *.exe~ diff --git a/publibike/stations.go b/publibike/stations.go new file mode 100644 index 0000000..bc45773 --- /dev/null +++ b/publibike/stations.go @@ -0,0 +1,69 @@ +package main + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "net/http" +) + +// Station struct to store station data +type Station 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"` +} + +// GetAllStations fetches data from /public/stations +func GetAllStations() ([]Station, 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 stations []Station + err = json.Unmarshal(body, &stations) + if err != nil { + return nil, fmt.Errorf("failed to unmarshal station: %w", err) + } + + return station, nil +} + +// GetStationByID fetches data from /public/stations/{id} +func GetStationByID(stationID int) (Station, error) { + url := fmt.Sprintf("https://api.publibike.ch/v1/public/stations/%d", stationID) + resp, err := http.Get(url) + if err != nil { + return Station{}, fmt.Errorf("failed to get station: %w", err) + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + return Station{}, fmt.Errorf("failed to read response body: %w", err) + } + + var station Station + err = json.Unmarshal(body, &response) + if err != nil { + return Station{}, fmt.Errorf("failed to unmarshal station: %w", err) + } + + return station, nil +}