flights

package
v0.0.0-...-3aa8757 Latest Latest
Warning

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

Go to latest
Published: Feb 18, 2024 License: MIT Imports: 23 Imported by: 1

Documentation

Overview

Package flights is a client library for the Google Flights API.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Args

type Args struct {
	Date, ReturnDate                               time.Time // start trip date and return date
	SrcCities, SrcAirports, DstCities, DstAirports []string  // source and destination; cities and airports of the trip
	Options                                                  // additional options
}

Arguments used in Session.GetOffers and Session.SerializeURL.

func (*Args) Convert

func (a *Args) Convert() PriceGraphArgs

Converts Args to PriceGraphArgs. It sets the date range to 30 days.

func (*Args) ValidateOffersArgs

func (a *Args) ValidateOffersArgs() error

Validates Offers arguments requirements:

  • at least one source location (srcCities / srcAirports)
  • at least one destination location (dstCities / dstAirports)
  • srcAirports and dstAirports have to be in the right IATA format: https://en.wikipedia.org/wiki/IATA_airport_code
  • dates have to be in chronological order: today's date -> Date -> ReturnDate

func (*Args) ValidateURLArgs

func (a *Args) ValidateURLArgs() error

Validates URL arguments requirements:

type Class

type Class int64

Class describes a travel class.

const (
	Economy Class = iota + 1
	PremiumEconomy
	Business
	First
)

type Flight

type Flight struct {
	DepAirportCode string        // departure airport code
	DepAirportName string        // departure airport name
	DepCity        string        // departure city
	ArrAirportName string        // arrival airport name
	ArrAirportCode string        // arrival airport code
	ArrCity        string        // arrival city
	DepTime        time.Time     // departure time
	ArrTime        time.Time     // arrival time
	Duration       time.Duration // duration of the flight
	Airplane       string        // airplane
	FlightNumber   string        // flight number
	Unknown        []interface{} // it contains all unknown data which are parsed from the Google Flights API
	AirlineName    string        // airline name
	Legroom        string        // legroom in the airplane seats
}

Flight describes a single, one-way flight.

func (Flight) String

func (f Flight) String() string

type FullOffer

type FullOffer struct {
	Offer
	Flight               []Flight      // contains all flights in the trip
	ReturnFlight         []Flight      // not implemented yet
	SrcAirportCode       string        // code of the airport where the trip starts
	DstAirportCode       string        // destination airport
	SrcCity              string        // source city
	DstCity              string        // destination city
	FlightDuration       time.Duration // duration of whole Flight
	ReturnFlightDuration time.Duration // not implemented yet
}

FullOffer describes the full offer of a trip. Session.GetOffers returns a slice of FullOffers.

NOTE: ReturnFlight is not implemented yet

func (FullOffer) String

func (o FullOffer) String() string

type Map

type Map[K comparable, V any] struct {
	// contains filtered or unexported fields
}

Map is safe for concurrent use by multiple goroutines. This is a wrapper around sync.Map. The purpose of it is to avoid type assertions when loading elements from the Map.

func (*Map[K, V]) Load

func (m *Map[K, V]) Load(key K) (value V, ok bool)

Load returns the value stored in the map for a key, or zero if no value is present. The ok result indicates whether value was found in the map.

func (*Map[K, V]) Store

func (m *Map[K, V]) Store(key K, value V)

Store sets the value for a key.

type Offer

type Offer struct {
	StartDate  time.Time // start date of the offer
	ReturnDate time.Time // return date of the offer
	Price      float64   // price of the offer
}

It describes the offer of a trip. Session.GetPriceGraph returns a slice of Offers. Session.GetOffers returns a slice of FullOffer that contains Offer.

func (Offer) String

func (o Offer) String() string

type Options

type Options struct {
	Travelers Travelers
	Currency  currency.Unit
	Stops     Stops        // maximum number of stops
	Class     Class        // travel class (Economy, PremiumEconomy, Business, First)
	TripType  TripType     // round-trip or one-way trip
	Lang      language.Tag // language in which city names are provided
}

Options contains common arguments used in Args and PriceGraphArgs.

func OptionsDefault

func OptionsDefault() Options

type PriceGraphArgs

type PriceGraphArgs struct {
	RangeStartDate, RangeEndDate                   time.Time // days range of the price graph
	TripLength                                     int       // number of days between start trip date and return date
	SrcCities, SrcAirports, DstCities, DstAirports []string  // source and destination; cities and airports of the trip
	Options                                                  // additional options
}

Arguments used in Session.GetPriceGraph.

func (*PriceGraphArgs) Convert

func (a *PriceGraphArgs) Convert() Args

Converts PriceGraphArgs to Args. It sets the date range to 30 days.

func (*PriceGraphArgs) Validate

func (a *PriceGraphArgs) Validate() error

Validates PriceGraphArgs requirements:

  • at least one source location (srcCities / srcAirports)
  • at least one destination location (dstCities / dstAirports)
  • srcAirports and dstAirports have to be in the right IATA format: https://en.wikipedia.org/wiki/IATA_airport_code
  • dates have to be in the chronological order: today's date -> RangeStartDate -> RangeEndDate
  • the difference between RangeStartDate and RangeEndDate cannot be higher than 161 days

type PriceRange

type PriceRange struct {
	Low  float64
	High float64
}

type Session

type Session struct {
	Cities Map[string, string] // Map which acts like a cache: city name -> abbravated city names
	// contains filtered or unexported fields
}

Session is the main type that contains all the most important functions to operate the Google Flights API. It is safe for concurrent use by multiple goroutines. (Concurrent example: github.com/krisukox/google-flights-api/examples/example3)

func New

func New() (*Session, error)

func (*Session) AbbrCity

func (s *Session) AbbrCity(ctx context.Context, city string, lang language.Tag) (string, error)

AbbrCity serializes the city name by requesting it from the Google Flights API. The city name should be provided in the language described by language.Tag.

AbbrCity returns an error if the city name is misspelled or the Google Flights API returns an unexpected response.

Example
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/krisukox/google-flights-api/flights"
	"golang.org/x/text/language"
)

func main() {
	session, err := flights.New()
	if err != nil {
		log.Fatal(err)
	}

	city, err := session.AbbrCity(context.Background(), "New York", language.English)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(city)
}
Output:

func (*Session) GetOffers

func (s *Session) GetOffers(ctx context.Context, args Args) ([]FullOffer, *PriceRange, error)

GetOffers retrieves offers from the Google Flight search. The city names should be provided in the language described by args.Lang. The offers are returned in a slice of FullOffer.

GetOffers also returns *PriceRange, which contains the low and high prices of the search. The values are taken from the "View price history" subsection of the search. If the search doesn't have the "View price history" subsection, then GetOffers returns nil.

GetPriceGraph returns an error if any of the requests fail or if any of the city names are misspelled.

Requirements are described by the Args.ValidateOffersArgs function.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/krisukox/google-flights-api/flights"
	"golang.org/x/text/currency"
	"golang.org/x/text/language"
)

func main() {
	session, err := flights.New()
	if err != nil {
		log.Fatal(err)
	}

	offers, priceRange, err := session.GetOffers(
		context.Background(),
		flights.Args{
			Date:       time.Now().AddDate(0, 0, 30),
			ReturnDate: time.Now().AddDate(0, 0, 37),
			SrcCities:  []string{"Madrid"},
			DstCities:  []string{"Estocolmo"},
			Options: flights.Options{
				Travelers: flights.Travelers{Adults: 2},
				Currency:  currency.EUR,
				Stops:     flights.Stop1,
				Class:     flights.Economy,
				TripType:  flights.RoundTrip,
				Lang:      language.Spanish,
			},
		},
	)
	if err != nil {
		log.Fatal(err)
	}

	if priceRange != nil {
		fmt.Printf("High price %d\n", int(priceRange.High))
		fmt.Printf("Low price %d\n", int(priceRange.Low))
	}
	fmt.Println(offers)
}
Output:

func (*Session) GetPriceGraph

func (s *Session) GetPriceGraph(ctx context.Context, args PriceGraphArgs) ([]Offer, error)

GetPriceGraph retrieves offers (date range) from the "Price graph" section of Google Flight search. The city names should be provided in the language described by args.Lang. The offers are returned in a slice of Offer.

GetPriceGraph returns an error if any of the requests fail or if any of the city names are misspelled.

Requirements are described by the PriceGraphArgs.Validate function.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/krisukox/google-flights-api/flights"
)

func main() {
	session, err := flights.New()
	if err != nil {
		log.Fatal(err)
	}

	offers, err := session.GetPriceGraph(
		context.Background(),
		flights.PriceGraphArgs{
			RangeStartDate: time.Now().AddDate(0, 0, 30),
			RangeEndDate:   time.Now().AddDate(0, 0, 60),
			TripLength:     7,
			SrcCities:      []string{"San Francisco"},
			DstCities:      []string{"New York"},
			Options:        flights.OptionsDefault(),
		},
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(offers)
}
Output:

func (*Session) IsIATASupported

func (s *Session) IsIATASupported(ctx context.Context, iataCode string) (bool, error)

IsIATASupported checks whether the provided IATA code is supported by the Google Flights API.

IsIATASupported returns an error if the Google Flights API returns an unexpected response.

func (*Session) SerializeURL

func (s *Session) SerializeURL(ctx context.Context, args Args) (string, error)

The function serializes arguments to the Google Flight URL. The city names should be provided in the language described by args.Lang. The args.Lang language is also used to set the language of the website to which the serialized URL leads.

GetPriceGraph returns an error if any of the requests fail or if any of the city names are misspelled.

Requirements are described by the Args.ValidateURLArgs function.

Example
package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"github.com/krisukox/google-flights-api/flights"
)

func main() {
	session, err := flights.New()
	if err != nil {
		log.Fatal(err)
	}

	url, err := session.SerializeURL(
		context.Background(),
		flights.Args{
			Date:        time.Now().AddDate(0, 0, 30),
			ReturnDate:  time.Now().AddDate(0, 0, 37),
			SrcCities:   []string{"San Diego"},
			SrcAirports: []string{"LAX"},
			DstCities:   []string{"New York", "Philadelphia"},
			Options:     flights.OptionsDefault(),
		},
	)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(url)
}
Output:

type Stops

type Stops int64

Stops specifies how many stops the trip should contain.

const (
	Nonstop  Stops = iota // nonstop only
	Stop1                 // 1 stop or fewer
	Stop2                 // 2 stops or fewer
	AnyStops              // any number of stops
)

type Travelers

type Travelers struct {
	Adults       int
	Children     int
	InfantInSeat int
	InfantOnLap  int
}

It describes travelers of the trip.

type TripType

type TripType int64

TripType specifies whether the trip is round-trip or one-way.

const (
	RoundTrip TripType = iota + 1
	OneWay
)

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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