gooctranspoapi

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 7, 2019 License: MIT Imports: 13 Imported by: 1

README

gooctranspoapi

Go Report Card godoc gopherbadger-tag-do-not-edit

A Go wrapper around the OC Transpo Live Next Bus Arrival Data Feed API.

The OC Transpo Developer documentation is available here: http://www.octranspo.com/developers/documentation

Example

Here's a small executable which queries the API for the next trips for a stop.

package main

import (
        "context"
        "flag"
        "fmt"
        api "github.com/transitreport/gooctranspoapi"
        "log"
        "os"
        "os/signal"
        "time"
)

var (
        id   = flag.String("id", "", "appID")
        key  = flag.String("key", "", "apiKey")
        stop = flag.String("stop", "", "stop number")
)

func main() {

        // Process the flags.
        flag.Parse()

        // If any of the required flags are not set, exit.
        if *id == "" {
                log.Fatalln("FATAL: An appID for the OC Transpo API is required.")
        } else if *key == "" {
                log.Fatalln("FATAL: An apiKey for the OC Transpo API is required.")
        } else if *stop == "" {
                log.Fatalln("FATAL: An stop number is required.")
        }

        // Create a new connection to the API, with a rate limit of 1 request per second,
        // with bursts of size 1.
        // Connections can also be created without a rate limit by using NewConnection()
        c := api.NewConnectionWithRateLimit(*id, *key, 1, 1)

        // Requests to the API have a context which can be canceled or timed out.
        ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
        defer cancel()

        // trap Ctrl+C and call cancel on the context
        sigChan := make(chan os.Signal, 1)
        signal.Notify(sigChan, os.Interrupt)
        defer signal.Stop(sigChan)
        go func() {
                select {
                case <-sigChan:
                        log.Println("Canceling requests...")
                        cancel()
                        log.Println("Done, bye!")
                case <-ctx.Done():
                }
        }()

        nextTripsAllRoutes, err := c.GetNextTripsForStopAllRoutes(ctx, *stop)
        if err != nil {
                log.Fatalln(err)
        }

        fmt.Printf("Stop %v, \"%v\":\n", nextTripsAllRoutes.StopNo, nextTripsAllRoutes.StopDescription)
        for _, route := range nextTripsAllRoutes.Routes {
                fmt.Printf("  Route %v, \"%v\", going %v:\n", route.RouteNo, route.RouteHeading, route.Direction)
                for _, trip := range route.Trips {
                        fmt.Printf("    %v (%v minutes old), %v\n", trip.AdjustedScheduleTime, trip.AdjustmentAge, trip.TripDestination)
                }
        }
}

Documentation

Overview

Package gooctranspoapi provides a Go wrapper around the OC Transpo Live Next Bus Arrival Data Feed API.

Index

Constants

View Source
const APIURLPrefix = "https://api.octranspo1.com/v1.3/"

APIURLPrefix is the address at which the API is available.

Variables

This section is empty.

Functions

func ColumnAndValue

func ColumnAndValue(column, value string) func(url.Values) error

ColumnAndValue will setup the request to return data from a specific column and value.

func Direction

func Direction(direction string) func(url.Values) error

Direction will setup the request to direction of sorted records, asc and desc.

func ID

func ID(id string) func(url.Values) error

ID will setup the request to return a specific row in a table by the id value.

func Limit

func Limit(limit int) func(url.Values) error

Limit will setup the request to only return a maximum number of records.

func OrderBy

func OrderBy(orderBy string) func(url.Values) error

OrderBy will setup the request to sort the data by a specific column.

Types

type Connection

type Connection struct {
	ID         string
	Key        string
	Limiter    *rate.Limiter
	HTTPClient *http.Client
	// contains filtered or unexported fields
}

Connection holds the Application ID and API key needed to make requests. It also has a rate limiter, used by the Connection's methods to limit calls on the API. The HTTP Client is a public field, so that it can be swapped out with a custom HTTP Client if needed.

func NewConnection

func NewConnection(id, key string) Connection

NewConnection returns a new connection without a rate limit.

func NewConnectionWithRateLimit

func NewConnectionWithRateLimit(id, key string, perSec float64, burst int) Connection

NewConnectionWithRateLimit returns a new connection with a rate limit set. This is helpful for ensuring you don't go over the daily call limit, which is usually 10,000 requests per day. It you use the connection over 24 hours, a connection with a perSec rate of 0.11572 would make around 9998 requests.

func (Connection) GetGTFSAgency

func (c Connection) GetGTFSAgency(ctx context.Context, options ...func(url.Values) error) (*GTFSAgency, error)

GetGTFSAgency returns the GTFS agency table.

func (Connection) GetGTFSCalendar

func (c Connection) GetGTFSCalendar(ctx context.Context, options ...func(url.Values) error) (*GTFSCalendar, error)

GetGTFSCalendar returns the GTFS calendar table.

func (Connection) GetGTFSCalendarDates

func (c Connection) GetGTFSCalendarDates(ctx context.Context, options ...func(url.Values) error) (*GTFSCalendarDates, error)

GetGTFSCalendarDates returns the GTFS calendar_dates table

func (Connection) GetGTFSRoutes

func (c Connection) GetGTFSRoutes(ctx context.Context, options ...func(url.Values) error) (*GTFSRoutes, error)

GetGTFSRoutes returns the GTFS routes table.

func (Connection) GetGTFSStopTimes

func (c Connection) GetGTFSStopTimes(ctx context.Context, options ...func(url.Values) error) (*GTFSStopTimes, error)

GetGTFSStopTimes returns the GTFS stop_times table. It requires a trip_id, stop_code or id value specified, using ColumnAndValue() or ID() options.

func (Connection) GetGTFSStops

func (c Connection) GetGTFSStops(ctx context.Context, options ...func(url.Values) error) (*GTFSStops, error)

GetGTFSStops returns the GTFS stops table. It requires a stop_id, stop_code or id value specified, using ColumnAndValue() or ID() options.

func (Connection) GetGTFSTrips

func (c Connection) GetGTFSTrips(ctx context.Context, options ...func(url.Values) error) (*GTFSTrips, error)

GetGTFSTrips returns the GTFS trips table. It requires a route_id or id value specified, using ColumnAndValue() or ID() options.

func (Connection) GetNextTripsForStop

func (c Connection) GetNextTripsForStop(ctx context.Context, routeNo, stopNo string) (*NextTripsForStop, error)

GetNextTripsForStop returns the next three trips on the route for a given stop number.

func (Connection) GetNextTripsForStopAllRoutes

func (c Connection) GetNextTripsForStopAllRoutes(ctx context.Context, stopNo string) (*NextTripsForStopAllRoutes, error)

GetNextTripsForStopAllRoutes returns the next three trips for all routes for a given stop number.

func (Connection) GetRouteSummaryForStop

func (c Connection) GetRouteSummaryForStop(ctx context.Context, stopNo string) (*RouteSummaryForStop, error)

GetRouteSummaryForStop returns the routes for a given stop number.

type GPSSpeed added in v0.4.0

type GPSSpeed struct {
	Set   bool
	Value float64
}

GPSSpeed stores both the data and if the data was set by the API

type GTFSAgency

type GTFSAgency struct {
	Query struct {
		Table     string `json:"table"`
		Direction string `json:"direction"`
		Format    string `json:"format"`
	} `json:"Query"`
	Gtfs []struct {
		ID             string `json:"id"`
		AgencyName     string `json:"agency_name"`
		AgencyURL      string `json:"agency_url"`
		AgencyTimezone string `json:"agency_timezone"`
		AgencyLang     string `json:"agency_lang"`
		AgencyPhone    string `json:"agency_phone"`
	} `json:"Gtfs"`
}

GTFSAgency is the GTFS agency table.

type GTFSCalendar

type GTFSCalendar struct {
	Query struct {
		Table     string `json:"table"`
		Direction string `json:"direction"`
		Format    string `json:"format"`
	} `json:"Query"`
	Gtfs []struct {
		ID        string `json:"id"`
		ServiceID string `json:"service_id"`
		Monday    string `json:"monday"`
		Tuesday   string `json:"tuesday"`
		Wednesday string `json:"wednesday"`
		Thursday  string `json:"thursday"`
		Friday    string `json:"friday"`
		Saturday  string `json:"saturday"`
		Sunday    string `json:"sunday"`
		StartDate string `json:"start_date"`
		EndDate   string `json:"end_date"`
	} `json:"Gtfs"`
}

GTFSCalendar is the GTFS calendar table.

type GTFSCalendarDates

type GTFSCalendarDates struct {
	Query struct {
		Table     string `json:"table"`
		Direction string `json:"direction"`
		Format    string `json:"format"`
	} `json:"Query"`
	Gtfs []struct {
		ID            string `json:"id"`
		ServiceID     string `json:"service_id"`
		Date          string `json:"date"`
		ExceptionType string `json:"exception_type"`
	} `json:"Gtfs"`
}

GTFSCalendarDates is GTFS calendar_dates table.

type GTFSRoutes

type GTFSRoutes struct {
	Query struct {
		Table     string `json:"table"`
		Direction string `json:"direction"`
		Format    string `json:"format"`
	} `json:"Query"`
	Gtfs []struct {
		ID             string `json:"id"`
		RouteID        string `json:"route_id"`
		RouteShortName string `json:"route_short_name"`
		RouteLongName  string `json:"route_long_name"`
		RouteDesc      string `json:"route_desc"`
		RouteType      string `json:"route_type"`
	} `json:"Gtfs"`
}

GTFSRoutes is the GTFS routes table.

type GTFSStopTimes

type GTFSStopTimes struct {
	Query struct {
		Table     string `json:"table"`
		Direction string `json:"direction"`
		Column    string `json:"column"`
		Value     string `json:"value"`
		Format    string `json:"format"`
	} `json:"Query"`
	Gtfs []struct {
		ID            string `json:"id"`
		TripID        string `json:"trip_id"`
		ArrivalTime   string `json:"arrival_time"`
		DepartureTime string `json:"departure_time"`
		StopID        string `json:"stop_id"`
		StopSequence  string `json:"stop_sequence"`
		PickupType    string `json:"pickup_type"`
		DropOffType   string `json:"drop_off_type"`
	} `json:"Gtfs"`
}

GTFSStopTimes is the GTFS stop_times table.

type GTFSStops

type GTFSStops struct {
	Query struct {
		Table     string `json:"table"`
		Direction string `json:"direction"`
		Column    string `json:"column"`
		Value     string `json:"value"`
		Format    string `json:"format"`
	} `json:"Query"`
	Gtfs []struct {
		ID            string `json:"id"`
		StopID        string `json:"stop_id"`
		StopCode      string `json:"stop_code"`
		StopName      string `json:"stop_name"`
		StopDesc      string `json:"stop_desc"`
		StopLat       string `json:"stop_lat"`
		StopLon       string `json:"stop_lon"`
		ZoneID        string `json:"zone_id"`
		StopURL       string `json:"stop_url"`
		LocationType  string `json:"location_type"`
		ParentStation string `json:"parent_station"`
	} `json:"Gtfs"`
}

GTFSStops is the GTFS stops table.

type GTFSTrips

type GTFSTrips struct {
	Query struct {
		Table     string `json:"table"`
		Direction string `json:"direction"`
		Column    string `json:"column"`
		Value     string `json:"value"`
		Format    string `json:"format"`
	} `json:"Query"`
	Gtfs []struct {
		ID           string `json:"id"`
		RouteID      string `json:"route_id"`
		ServiceID    string `json:"service_id"`
		TripID       string `json:"trip_id"`
		TripHeadsign string `json:"trip_headsign"`
		DirectionID  string `json:"direction_id"`
		BlockID      string `json:"block_id"`
	} `json:"Gtfs"`
}

GTFSTrips is the GTFS trips table.

type LastTripOfSchedule added in v0.4.0

type LastTripOfSchedule struct {
	Set   bool
	Value bool
}

LastTripOfSchedule stores both the data and if the data was set by the API

type Latitude added in v0.4.0

type Latitude struct {
	Set   bool
	Value float64
}

Latitude stores both the data and if the data was set by the API

type Longitude added in v0.4.0

type Longitude struct {
	Set   bool
	Value float64
}

Longitude stores both the data and if the data was set by the API

type NextTripsForStop

type NextTripsForStop struct {
	StopNo          string
	StopLabel       string
	Error           string
	RouteDirections []RouteDirection
}

NextTripsForStop is a simplified version of the data returned by a request to GetNextTripsForStop

type NextTripsForStopAllRoutes

type NextTripsForStopAllRoutes struct {
	StopNo          string
	StopDescription string
	Error           string
	Routes          []RouteWithTrips
}

NextTripsForStopAllRoutes is a simplified version of the data returned by a request to GetNextTripsForStopAllRoutes

type Route added in v0.2.0

type Route struct {
	RouteNo      string
	DirectionID  string
	Direction    string
	RouteHeading string
}

Route is used by RouteSummaryForStop to store route data.

type RouteDirection added in v0.4.0

type RouteDirection struct {
	RouteNo               string
	RouteLabel            string
	Direction             string
	Error                 string
	RequestProcessingTime time.Time
	Trips                 []Trip
}

RouteDirection is used by NextTripsForStop to store route direction data.

type RouteSummaryForStop

type RouteSummaryForStop struct {
	StopNo          string
	StopDescription string
	Error           string
	Routes          []Route
}

RouteSummaryForStop is a simplified version of the data returned by a request to GetRouteSummaryForStop.

type RouteWithTrips added in v0.4.0

type RouteWithTrips struct {
	RouteNo      string
	DirectionID  string
	Direction    string
	RouteHeading string
	Trips        []Trip
}

RouteWithTrips is used by NextTripsForStopAllRoutes to store route data.

type Trip added in v0.4.0

type Trip struct {
	TripDestination      string
	TripStartTime        string
	AdjustedScheduleTime int
	AdjustmentAge        float64
	LastTripOfSchedule
	BusType string
	Latitude
	Longitude
	GPSSpeed
}

Trip stores trip data, and includes the adjusted schedule time.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL