Documentation
¶
Overview ¶
Package flightradarapi is an unofficial SDK for FlightRadar24.
It provides the flight and airport data available to the public on the FlightRadar24 website. Start with New, then call the methods of Client.
See more information at:
https://www.flightradar24.com/premium/ https://www.flightradar24.com/terms-and-conditions
Porting from the Python and Node.js SDKs ¶
The three SDKs carry the same features; the names differ only where Go's conventions do. The package name is part of every identifier here, so the client is Client rather than FlightRadar24API, the way it is http.Client and not http.HTTPClient.
Python / Node.js This package
------------------------ --------------------------------------------
FlightRadar24API() New(), returning a *Client
FlightRadar24API({...}) New(Options{...})
FlightRadarError ErrFlightRadar, wrapped by every error here
Countries.BRAZIL CountryBrazil, with AllCountries() to enumerate
get_flights(airline, ...) Client.GetFlights(ctx, FlightSearch{...})
check_info(min_altitude=x) Flight.CheckInfo(map[string]any{"min_altitude": x})
Airport.from_details(x) NewAirportFromDetails(x)
(bytes, extension) tuple *Image
airline["n_aircrafts"] Airline.NumAircrafts
flight.destination_... flight.Details.Destination...
Every method of FlightRadar24API has a counterpart here with the same parameters, and a test reads the Python source to keep it that way.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
client := flightradarapi.New()
flights, err := client.GetFlights(context.Background(), flightradarapi.FlightSearch{})
if err != nil {
log.Fatal(err)
}
for _, flight := range flights[:min(5, len(flights))] {
fmt.Println(flight.Callsign, flight.GetFlightLevel(), flight.GetGroundSpeed())
}
}
Output:
Index ¶
- Constants
- Variables
- func SetLogger(l *slog.Logger)
- type Airline
- type Airport
- type AirportNotFoundError
- type Client
- func (c *Client) GetAirlineLogo(ctx context.Context, iata, icao string) (*Image, error)
- func (c *Client) GetAirlines(ctx context.Context) ([]Airline, error)
- func (c *Client) GetAirport(ctx context.Context, code string, details bool) (*Airport, error)
- func (c *Client) GetAirportDetails(ctx context.Context, code string, flightLimit, page int) (map[string]any, error)
- func (c *Client) GetAirportDisruptions(ctx context.Context) (map[string]any, error)
- func (c *Client) GetAirports(ctx context.Context, countries []Country) ([]*Airport, error)
- func (c *Client) GetBookmarks(ctx context.Context) (map[string]any, error)
- func (c *Client) GetBounds(zone Zone) string
- func (c *Client) GetBoundsByPoint(latitude, longitude, radius float64) string
- func (c *Client) GetCountryFlag(ctx context.Context, country string) (*Image, error)
- func (c *Client) GetFlightDetails(ctx context.Context, flight *Flight) (map[string]any, error)
- func (c *Client) GetFlightTrackerConfig() FlightTrackerConfig
- func (c *Client) GetFlights(ctx context.Context, search FlightSearch) ([]*Flight, error)
- func (c *Client) GetHistoryData(ctx context.Context, flight *Flight, fileType string, timestamp int64) (string, error)
- func (c *Client) GetLoginData() (map[string]any, error)
- func (c *Client) GetMostTracked(ctx context.Context) (map[string]any, error)
- func (c *Client) GetVolcanicEruptions(ctx context.Context) (map[string]any, error)
- func (c *Client) GetZones() map[string]Zone
- func (c *Client) IsLoggedIn() bool
- func (c *Client) Login(ctx context.Context, user, password string) error
- func (c *Client) Logout(ctx context.Context) (bool, error)
- func (c *Client) Search(ctx context.Context, query string, limit int) (map[string][]any, error)
- func (c *Client) SetFlightTrackerConfig(config *FlightTrackerConfig, values map[string]string) error
- type CloudflareError
- type Country
- type DecompressionLimitError
- type Entity
- type Flight
- func (f *Flight) CheckInfo(criteria map[string]any) (bool, error)
- func (f *Flight) GetAltitude() string
- func (f *Flight) GetFlightLevel() string
- func (f *Flight) GetGroundSpeed() string
- func (f *Flight) GetHeading() string
- func (f *Flight) GetVerticalSpeed() string
- func (f *Flight) SetFlightDetails(flightDetails map[string]any)
- func (f *Flight) String() string
- type FlightDetails
- type FlightSearch
- type FlightTrackerConfig
- type Image
- type LoginError
- type Options
- type Positioned
- type Response
- type RetryPolicy
- type StatusError
- type TLSProfile
- type Zone
Examples ¶
Constants ¶
const ( DefaultRetryBaseDelay = time.Second DefaultRetryMaxDelay = 30 * time.Second DefaultRetryJitter = 500 * time.Millisecond )
Defaults the Python and Node.js ports declare in their RetryPolicy constructors, used here for any field left at zero.
const Author = "Jean Loui Bernard Silva de Jesus"
Author of this package.
const DefaultText = "N/A"
DefaultText is the placeholder the Get* formatters return for a value the feed did not send.
const DefaultTimeout = 30 * time.Second
DefaultTimeout is the per-request timeout when none is given.
const MaxResponseBytes = 64 * 1024 * 1024
MaxResponseBytes is the default budget for a response body, before and after decompression. A compressed body is trusted only as far as its expanded size: brotli reaches ratios high enough to exhaust memory from a few kilobytes on the wire.
const Version = "1.6.1"
Version of this package.
Variables ¶
var ( ErrFlightRadar = errors.New("flightradar24") ErrAirportNotFound = fmt.Errorf("%w: airport not found", ErrFlightRadar) ErrCloudflare = fmt.Errorf("%w: blocked by cloudflare", ErrFlightRadar) ErrDecompressionLimit = fmt.Errorf("%w: response body past the size limit", ErrFlightRadar) ErrLogin = fmt.Errorf("%w: login", ErrFlightRadar) )
Sentinels for the package's error taxonomy. Every error returned by this package wraps ErrFlightRadar, so errors.Is(err, ErrFlightRadar) matches all of them — the counterpart of catching the FlightRadarError base class in the Python and Node.js SDKs.
Functions ¶
func SetLogger ¶
SetLogger routes this package's warnings to l, process-wide; nil restores the default. Without it, slog.Default() is used, so an application that configures slog receives them without calling this at all.
Package-scoped rather than per-client on purpose: every message here reports that FR24 changed a payload's shape, which is true for the whole process. The Python and Node.js ports use a module logger for the same reason.
Types ¶
type Airline ¶
type Airline struct {
Name string `json:"Name"`
ICAO string `json:"ICAO"`
IATA string `json:"IATA"`
NumAircrafts *int `json:"n_aircrafts"`
}
Airline is one row of the airlines listing. The JSON tags match the keys the Python and Node.js ports use, so NumAircrafts serialises as "n_aircrafts".
type Airport ¶
type Airport struct {
Entity
Name string
ICAO string
IATA string
Altitude *float64
Country string
CountryCode string
CountryID *float64
City string
TimezoneName string
TimezoneOffset *float64
TimezoneOffsetHours string
TimezoneAbbr string
TimezoneAbbrName string
Visible *bool
Website string
Wikipedia string
ReviewsURL string
Reviews *float64
Evaluation *float64
AverageRating *float64
TotalRating *float64
Weather map[string]any
Runways []any
AircraftOnGround *float64
AircraftVisibleOnGround *float64
Arrivals map[string]any
Departures map[string]any
Images map[string]any
// RawDetails is the payload the details came from, for fields this struct
// does not name.
RawDetails map[string]any
}
Airport is an airport, with whatever detail the call that produced it carried. Fields past Country are filled in by Client.GetAirport with details, or by SetAirportDetails.
func NewAirport ¶
func NewAirport() *Airport
NewAirport returns an empty airport, to be filled in with SetAirportDetails.
func NewAirportFromBasicInfo ¶
NewAirportFromBasicInfo builds an airport from one row of the airports feed, the counterpart of Airport.from_basic_info in the Python and Node.js ports. A row with only one usable coordinate carries no position at all.
func NewAirportFromDetails ¶
NewAirportFromDetails builds an airport from a full Client.GetAirportDetails payload, the counterpart of Airport.from_details.
func NewAirportFromInfo ¶
NewAirportFromInfo builds an airport from the traffic-stats "details" block, the counterpart of Airport.from_info.
func (*Airport) SetAirportDetails ¶
SetAirportDetails fills the airport in from a Client.GetAirportDetails payload.
type AirportNotFoundError ¶
type AirportNotFoundError struct {
Code string
Message string
// Errors carries the FR24 validation payload, when the API returned one.
Errors map[string]any
}
AirportNotFoundError reports a code no airport answered to.
func (*AirportNotFoundError) Error ¶
func (e *AirportNotFoundError) Error() string
func (*AirportNotFoundError) Unwrap ¶
func (e *AirportNotFoundError) Unwrap() error
type Client ¶
type Client struct {
// Timeout bounds a single request, and MaxWorkers the concurrent detail
// requests GetFlights makes. Set them through [New], or directly before the
// first call: they are read from the worker goroutines GetFlights spawns, so
// changing one while a request is in flight is a data race.
Timeout time.Duration
MaxWorkers int
// contains filtered or unexported fields
}
Client is the main entry point of the package, the counterpart of the FlightRadar24API class in the Python and Node.js SDKs. Build one with New.
func New ¶
New returns a client, taking at most one Options; anything past the first is ignored. Call Client.Login for the endpoints that need an account.
Construction cannot fail, so there is no error to handle: an unusable value falls back to the documented default.
func (*Client) GetAirlineLogo ¶
GetAirlineLogo downloads the logo of an airline, or returns nil when FR24 has none.
func (*Client) GetAirlines ¶
GetAirlines returns every airline.
func (*Client) GetAirport ¶
GetAirport returns basic information about an airport. With details, it makes the extra call Client.GetAirportDetails does.
Example (Details) ¶
package main
import (
"context"
"errors"
"fmt"
"log"
"time"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
client := flightradarapi.New(flightradarapi.Options{Timeout: 10 * time.Second})
airport, err := client.GetAirport(context.Background(), "VNLK", true)
if errors.Is(err, flightradarapi.ErrAirportNotFound) {
fmt.Println("no such airport")
return
}
if err != nil {
log.Fatal(err)
}
fmt.Println(airport.Name, airport.TimezoneName, len(airport.Runways))
}
Output:
func (*Client) GetAirportDetails ¶
func (c *Client) GetAirportDetails(ctx context.Context, code string, flightLimit, page int) (map[string]any, error)
GetAirportDetails returns the full airport payload, with up to flightLimit flights from the given page of results. Zero means what the Python and Node.js ports default to: 100 flights, first page. Any other value is sent as given, so FR24 rejects a nonsensical one rather than this package hiding it.
func (*Client) GetAirportDisruptions ¶
GetAirportDisruptions returns the current airport disruptions.
func (*Client) GetAirports ¶
GetAirports returns every airport, or only those of the given countries. Pass nil for every airport; an empty non-nil slice selects none.
Example ¶
package main
import (
"context"
"fmt"
"log"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
client := flightradarapi.New()
// Pass nil for every airport in the feed.
airports, err := client.GetAirports(context.Background(), []flightradarapi.Country{
flightradarapi.CountryBrazil,
flightradarapi.CountryUnitedStates,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(len(airports), "airports")
}
Output:
func (*Client) GetBookmarks ¶
GetBookmarks returns the bookmarks of the logged-in account.
func (*Client) GetBounds ¶
GetBounds renders a zone as the "y1,y2,x1,x2" string the feed expects.
Example ¶
package main
import (
"fmt"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
client := flightradarapi.New()
// The zones are bundled, so this needs no request.
fmt.Println(client.GetBounds(client.GetZones()["europe"]))
}
Output: 72.57,33.57,-16.96,53.05
func (*Client) GetBoundsByPoint ¶
GetBoundsByPoint renders the square of the given radius (in meters) around a point as the "y1,y2,x1,x2" string the feed expects.
func (*Client) GetCountryFlag ¶
GetCountryFlag downloads the flag of a country, or returns nil when FR24 has none.
func (*Client) GetFlightDetails ¶
GetFlightDetails returns the details payload of a flight.
func (*Client) GetFlightTrackerConfig ¶
func (c *Client) GetFlightTrackerConfig() FlightTrackerConfig
GetFlightTrackerConfig returns a copy of the current Real Time Flight Tracker config, used by Client.GetFlights.
func (*Client) GetFlights ¶
GetFlights returns the flights the live feed reports for the given search.
Example (AbovePosition) ¶
package main
import (
"context"
"fmt"
"log"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
client := flightradarapi.New()
// Your point is 52°34'04.7"N 13°16'57.5"E from Google Maps, and a radius of
// 2 km around it.
bounds := client.GetBoundsByPoint(52.567774, 13.282827, 2000)
flights, err := client.GetFlights(context.Background(), flightradarapi.FlightSearch{
Bounds: bounds,
})
if err != nil {
log.Fatal(err)
}
fmt.Println(len(flights), "flights overhead")
}
Output:
Example (WithDetails) ¶
package main
import (
"context"
"fmt"
"log"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
client := flightradarapi.New(flightradarapi.Options{MaxWorkers: 4})
// One extra request per flight, four at a time.
flights, err := client.GetFlights(context.Background(), flightradarapi.FlightSearch{
Airline: "GLO",
Details: true,
})
if err != nil {
log.Fatal(err)
}
for _, flight := range flights {
fmt.Println(flight.Callsign, "→", flight.Details.DestinationAirportName)
}
}
Output:
func (*Client) GetHistoryData ¶
func (c *Client) GetHistoryData(ctx context.Context, flight *Flight, fileType string, timestamp int64) (string, error)
GetHistoryData downloads the historical data of a flight. fileType must be "CSV" or "KML". Requires a premium account.
func (*Client) GetLoginData ¶
GetLoginData returns the data of the logged-in account.
func (*Client) GetMostTracked ¶
GetMostTracked returns the most tracked flights.
func (*Client) GetVolcanicEruptions ¶
GetVolcanicEruptions returns the boundaries of volcanic eruptions and ash clouds impacting aviation.
func (*Client) IsLoggedIn ¶
IsLoggedIn reports whether the client holds a FlightRadar24 session.
func (*Client) Login ¶
Login logs in to a FlightRadar24 account.
Example ¶
package main
import (
"context"
"fmt"
"log"
"time"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
client := flightradarapi.New()
if err := client.Login(context.Background(), "email", "password"); err != nil {
log.Fatal(err)
}
defer client.Logout(context.Background())
// Downloading history data needs a premium account.
data, err := client.GetHistoryData(context.Background(), &flightradarapi.Flight{ID: "2e0f1a2"},
"CSV", time.Now().Unix())
if err != nil {
log.Fatal(err)
}
fmt.Println(len(data), "bytes of history")
}
Output:
func (*Client) Logout ¶
Logout ends the FlightRadar24 session, reporting whether the server confirmed it.
func (*Client) Search ¶
Search returns the search results, grouped as FR24 counts them. A limit of zero means the 50 the Python and Node.js ports default to; any other value is sent as given.
func (*Client) SetFlightTrackerConfig ¶
func (c *Client) SetFlightTrackerConfig(config *FlightTrackerConfig, values map[string]string) error
SetFlightTrackerConfig replaces the config, then applies values on top of it. Either argument may be nil.
type CloudflareError ¶
type CloudflareError struct {
Message string
// Response is the blocked response, with Body already drained.
Response *http.Response
// Body is the challenge page, kept readable after the drain.
Body []byte
}
CloudflareError reports a block by Cloudflare rather than by the FR24 origin.
func (*CloudflareError) Error ¶
func (e *CloudflareError) Error() string
func (*CloudflareError) Unwrap ¶
func (e *CloudflareError) Unwrap() error
type Country ¶
type Country string
Country is a FlightRadar24 country slug, accepted by Client.GetAirports, and the counterpart of the Countries enum in the Python and Node.js SDKs: what they spell Countries.BRAZIL is CountryBrazil here.
Any spelling works: values are slugified before matching, so Country("Myanmar (Burma)") is the same filter as CountryMyanmarBurma.
const ( CountryAfghanistan Country = "afghanistan" CountryAlbania Country = "albania" CountryAlgeria Country = "algeria" CountryAmericanSamoa Country = "american-samoa" CountryAngola Country = "angola" CountryAnguilla Country = "anguilla" CountryAntarctica Country = "antarctica" CountryAntiguaAndBarbuda Country = "antigua-and-barbuda" CountryArgentina Country = "argentina" CountryArmenia Country = "armenia" CountryAruba Country = "aruba" CountryAustralia Country = "australia" CountryAustria Country = "austria" CountryAzerbaijan Country = "azerbaijan" CountryBahamas Country = "bahamas" CountryBahrain Country = "bahrain" CountryBangladesh Country = "bangladesh" CountryBarbados Country = "barbados" CountryBelarus Country = "belarus" CountryBelgium Country = "belgium" CountryBelize Country = "belize" CountryBenin Country = "benin" CountryBermuda Country = "bermuda" CountryBhutan Country = "bhutan" CountryBolivia Country = "bolivia" CountryBosniaAndHerzegovina Country = "bosnia-and-herzegovina" CountryBotswana Country = "botswana" CountryBrazil Country = "brazil" CountryBrunei Country = "brunei" CountryBulgaria Country = "bulgaria" CountryBurkinaFaso Country = "burkina-faso" CountryBurundi Country = "burundi" CountryCambodia Country = "cambodia" CountryCameroon Country = "cameroon" CountryCanada Country = "canada" CountryCapeVerde Country = "cape-verde" CountryCaymanIslands Country = "cayman-islands" CountryCentralAfricanRepublic Country = "central-african-republic" CountryChad Country = "chad" CountryChile Country = "chile" CountryChina Country = "china" CountryCocosKeelingIslands Country = "cocos-keeling-islands" CountryColombia Country = "colombia" CountryComoros Country = "comoros" CountryCongo Country = "congo" CountryCookIslands Country = "cook-islands" CountryCostaRica Country = "costa-rica" CountryCroatia Country = "croatia" CountryCuba Country = "cuba" CountryCuracao Country = "curacao" CountryCyprus Country = "cyprus" CountryCzechia Country = "czechia" CountryDemocraticRepublicOfTheCongo Country = "democratic-republic-of-the-congo" CountryDenmark Country = "denmark" CountryDjibouti Country = "djibouti" CountryDominica Country = "dominica" CountryDominicanRepublic Country = "dominican-republic" CountryEcuador Country = "ecuador" CountryEgypt Country = "egypt" CountryElSalvador Country = "el-salvador" CountryEquatorialGuinea Country = "equatorial-guinea" CountryEritrea Country = "eritrea" CountryEstonia Country = "estonia" CountryEswatini Country = "eswatini" CountryEthiopia Country = "ethiopia" CountryFalklandIslandsMalvinas Country = "falkland-islands-malvinas" CountryFaroeIslands Country = "faroe-islands" CountryFiji Country = "fiji" CountryFinland Country = "finland" CountryFrance Country = "france" CountryFrenchGuiana Country = "french-guiana" CountryFrenchPolynesia Country = "french-polynesia" CountryGabon Country = "gabon" CountryGambia Country = "gambia" CountryGeorgia Country = "georgia" CountryGermany Country = "germany" CountryGhana Country = "ghana" CountryGibraltar Country = "gibraltar" CountryGreece Country = "greece" CountryGreenland Country = "greenland" CountryGrenada Country = "grenada" CountryGuadeloupe Country = "guadeloupe" CountryGuam Country = "guam" CountryGuatemala Country = "guatemala" CountryGuernsey Country = "guernsey" CountryGuinea Country = "guinea" CountryGuineaBissau Country = "guinea-bissau" CountryGuyana Country = "guyana" CountryHaiti Country = "haiti" CountryHonduras Country = "honduras" CountryHongKong Country = "hong-kong" CountryHungary Country = "hungary" CountryIceland Country = "iceland" CountryIndia Country = "india" CountryIndonesia Country = "indonesia" CountryIran Country = "iran" CountryIraq Country = "iraq" CountryIreland Country = "ireland" CountryIsleOfMan Country = "isle-of-man" CountryIsrael Country = "israel" CountryItaly Country = "italy" CountryIvoryCoast Country = "ivory-coast" CountryJamaica Country = "jamaica" CountryJapan Country = "japan" CountryJersey Country = "jersey" CountryJordan Country = "jordan" CountryKazakhstan Country = "kazakhstan" CountryKenya Country = "kenya" CountryKiribati Country = "kiribati" CountryKosovo Country = "kosovo" CountryKuwait Country = "kuwait" CountryKyrgyzstan Country = "kyrgyzstan" CountryLaos Country = "laos" CountryLatvia Country = "latvia" CountryLebanon Country = "lebanon" CountryLesotho Country = "lesotho" CountryLiberia Country = "liberia" CountryLibya Country = "libya" CountryLithuania Country = "lithuania" CountryLuxembourg Country = "luxembourg" CountryMacao Country = "macao" CountryMadagascar Country = "madagascar" CountryMalawi Country = "malawi" CountryMalaysia Country = "malaysia" CountryMaldives Country = "maldives" CountryMali Country = "mali" CountryMalta Country = "malta" CountryMarshallIslands Country = "marshall-islands" CountryMartinique Country = "martinique" CountryMauritania Country = "mauritania" CountryMauritius Country = "mauritius" CountryMayotte Country = "mayotte" CountryMexico Country = "mexico" CountryMicronesia Country = "micronesia" CountryMoldova Country = "moldova" CountryMonaco Country = "monaco" CountryMongolia Country = "mongolia" CountryMontenegro Country = "montenegro" CountryMontserrat Country = "montserrat" CountryMorocco Country = "morocco" CountryMozambique Country = "mozambique" CountryMyanmarBurma Country = "myanmar-burma" CountryNamibia Country = "namibia" CountryNauru Country = "nauru" CountryNepal Country = "nepal" CountryNetherlands Country = "netherlands" CountryNewCaledonia Country = "new-caledonia" CountryNewZealand Country = "new-zealand" CountryNicaragua Country = "nicaragua" CountryNiger Country = "niger" CountryNigeria Country = "nigeria" CountryNorthKorea Country = "north-korea" CountryNorthMacedonia Country = "north-macedonia" CountryNorthernMarianaIslands Country = "northern-mariana-islands" CountryNorway Country = "norway" CountryOman Country = "oman" CountryPakistan Country = "pakistan" CountryPalau Country = "palau" CountryPanama Country = "panama" CountryPapuaNewGuinea Country = "papua-new-guinea" CountryParaguay Country = "paraguay" CountryPeru Country = "peru" CountryPhilippines Country = "philippines" CountryPoland Country = "poland" CountryPortugal Country = "portugal" CountryPuertoRico Country = "puerto-rico" CountryQatar Country = "qatar" CountryReunion Country = "reunion" CountryRomania Country = "romania" CountryRussia Country = "russia" CountryRwanda Country = "rwanda" CountrySaintHelena Country = "saint-helena" CountrySaintKittsAndNevis Country = "saint-kitts-and-nevis" CountrySaintLucia Country = "saint-lucia" CountrySaintPierreAndMiquelon Country = "saint-pierre-and-miquelon" CountrySaintVincentAndTheGrenadines Country = "saint-vincent-and-the-grenadines" CountrySamoa Country = "samoa" CountrySaoTomeAndPrincipe Country = "sao-tome-and-principe" CountrySaudiArabia Country = "saudi-arabia" CountrySenegal Country = "senegal" CountrySerbia Country = "serbia" CountrySeychelles Country = "seychelles" CountrySierraLeone Country = "sierra-leone" CountrySingapore Country = "singapore" CountrySlovakia Country = "slovakia" CountrySlovenia Country = "slovenia" CountrySolomonIslands Country = "solomon-islands" CountrySomalia Country = "somalia" CountrySouthAfrica Country = "south-africa" CountrySouthKorea Country = "south-korea" CountrySouthSudan Country = "south-sudan" CountrySpain Country = "spain" CountrySriLanka Country = "sri-lanka" CountrySudan Country = "sudan" CountrySuriname Country = "suriname" CountrySweden Country = "sweden" CountrySwitzerland Country = "switzerland" CountrySyria Country = "syria" CountryTaiwan Country = "taiwan" CountryTajikistan Country = "tajikistan" CountryTanzania Country = "tanzania" CountryThailand Country = "thailand" CountryTimorLesteEastTimor Country = "timor-leste-east-timor" CountryTogo Country = "togo" CountryTonga Country = "tonga" CountryTrinidadAndTobago Country = "trinidad-and-tobago" CountryTunisia Country = "tunisia" CountryTurkey Country = "turkey" CountryTurkmenistan Country = "turkmenistan" CountryTurksAndCaicosIslands Country = "turks-and-caicos-islands" CountryTuvalu Country = "tuvalu" CountryUganda Country = "uganda" CountryUkraine Country = "ukraine" CountryUnitedArabEmirates Country = "united-arab-emirates" CountryUnitedKingdom Country = "united-kingdom" CountryUnitedStates Country = "united-states" CountryUnitedStatesMinorOutlyingIslands Country = "united-states-minor-outlying-islands" CountryUruguay Country = "uruguay" CountryUzbekistan Country = "uzbekistan" CountryVanuatu Country = "vanuatu" CountryVenezuela Country = "venezuela" CountryVietnam Country = "vietnam" CountryVirginIslandsBritish Country = "virgin-islands-british" CountryVirginIslandsUs Country = "virgin-islands-us" CountryWallisAndFutuna Country = "wallis-and-futuna" CountryYemen Country = "yemen" CountryZambia Country = "zambia" CountryZimbabwe Country = "zimbabwe" )
Country slugs, as FlightRadar24 spells them in its data page URLs.
func AllCountries ¶
func AllCountries() []Country
AllCountries returns every country above, in the order FR24 declares them — what list(Countries) gives in the Python port. The slice is a fresh copy, so a caller sorting or filtering it cannot corrupt the package's own data.
type DecompressionLimitError ¶
type DecompressionLimitError struct {
Message string
}
DecompressionLimitError reports a body that grew past the size budget.
func (*DecompressionLimitError) Error ¶
func (e *DecompressionLimitError) Error() string
func (*DecompressionLimitError) Unwrap ¶
func (e *DecompressionLimitError) Unwrap() error
type Entity ¶
type Entity struct {
// Latitude and Longitude are nil when the feed sent no usable position.
Latitude *float64
Longitude *float64
}
Entity is a real entity at some location. Both Airport and Flight embed it.
func (Entity) GetDistanceFrom ¶
func (e Entity) GetDistanceFrom(other Positioned) (float64, error)
GetDistanceFrom returns the distance from another entity, in kilometers.
Example ¶
package main
import (
"fmt"
"log"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
latitude, longitude := -23.43, -46.47
airport := &flightradarapi.Airport{
IATA: "GRU",
Entity: flightradarapi.Entity{Latitude: &latitude, Longitude: &longitude},
}
flightLatitude, flightLongitude := -22.81, -43.25
flight := &flightradarapi.Flight{
Entity: flightradarapi.Entity{Latitude: &flightLatitude, Longitude: &flightLongitude},
}
distance, err := airport.GetDistanceFrom(flight)
if err != nil {
log.Fatal(err)
}
fmt.Printf("%.0f km\n", distance)
}
Output: 336 km
type Flight ¶
type Flight struct {
Entity
ID string
ICAO24Bit string
// Heading, Altitude, GroundSpeed and VerticalSpeed are nil when the feed
// sent no value.
Heading *float64
Altitude *float64
GroundSpeed *float64
Squawk string
AircraftCode string
Registration string
Time *int64
OriginAirportIATA string
DestinationAirportIATA string
Number string
AirlineIATA string
// OnGround is 1 while the aircraft is on the ground.
OnGround *float64
VerticalSpeed *float64
Callsign string
AirlineICAO string
Details *FlightDetails
}
Flight is a flight from the Real Time Flight Tracker. Details holds the extra information Client.GetFlightDetails returns, once SetFlightDetails is called.
func NewFlight ¶
NewFlight builds a flight from one entry of the live feed, the counterpart of the Flight(flight_id, info) constructor in the Python and Node.js ports.
func (*Flight) CheckInfo ¶
CheckInfo checks one or more flight values. A key may carry a "min_" or "max_" prefix to compare numerically instead of for equality:
flight.CheckInfo(map[string]any{"min_altitude": 6700, "airline_icao": "THY"})
Detail names such as "airline_name" work once SetFlightDetails has run. A name that exists nowhere is an error, where the Python and Node.js ports ignore it and report a match the caller never asked for.
Example ¶
package main
import (
"fmt"
"log"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
altitude, groundSpeed := 12000.0, 430.0
flight := &flightradarapi.Flight{
Callsign: "THY1",
AirlineICAO: "THY",
Altitude: &altitude,
GroundSpeed: &groundSpeed,
}
// "min_" and "max_" compare numerically; anything else compares for equality.
matched, err := flight.CheckInfo(map[string]any{
"min_altitude": 6700,
"max_altitude": 13000,
"airline_icao": "THY",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(matched, flight.GetFlightLevel())
}
Output: true 120 FL
func (*Flight) GetAltitude ¶
GetAltitude returns the formatted altitude, with its unit.
func (*Flight) GetFlightLevel ¶
GetFlightLevel returns the formatted flight level, with its unit.
func (*Flight) GetGroundSpeed ¶
GetGroundSpeed returns the formatted ground speed, with its unit.
func (*Flight) GetHeading ¶
GetHeading returns the formatted heading, with its unit.
func (*Flight) GetVerticalSpeed ¶
GetVerticalSpeed returns the formatted vertical speed, with its unit.
func (*Flight) SetFlightDetails ¶
SetFlightDetails fills Details in from a Client.GetFlightDetails payload.
type FlightDetails ¶
type FlightDetails struct {
AircraftAge string
AircraftCountryID *float64
AircraftHistory []any
AircraftImages any
AircraftModel string
AirlineName string
AirlineShortName string
DestinationAirportAltitude *float64
DestinationAirportCountryCode string
DestinationAirportCountryName string
DestinationAirportLatitude *float64
DestinationAirportLongitude *float64
DestinationAirportICAO string
DestinationAirportBaggage string
DestinationAirportGate string
DestinationAirportName string
DestinationAirportTerminal string
DestinationAirportVisible *bool
DestinationAirportWebsite string
DestinationAirportTimezoneAbbr string
DestinationAirportTimezoneAbbrName string
DestinationAirportTimezoneName string
DestinationAirportTimezoneOffset *float64
DestinationAirportTimezoneOffsetHours string
OriginAirportAltitude *float64
OriginAirportCountryCode string
OriginAirportCountryName string
OriginAirportLatitude *float64
OriginAirportLongitude *float64
OriginAirportICAO string
OriginAirportBaggage string
OriginAirportGate string
OriginAirportName string
OriginAirportTerminal string
OriginAirportVisible *bool
OriginAirportWebsite string
OriginAirportTimezoneAbbr string
OriginAirportTimezoneAbbrName string
OriginAirportTimezoneName string
OriginAirportTimezoneOffset *float64
OriginAirportTimezoneOffsetHours string
StatusIcon string
StatusText string
TimeDetails map[string]any
Trail []any
// Raw is the payload these fields came from.
Raw map[string]any
}
FlightDetails is the extra information carried by a flight details payload.
type FlightSearch ¶
type FlightSearch struct {
// Airline is an airline ICAO, e.g. "DAL".
Airline string
// Bounds is a "y1,y2,x1,x2" string, e.g. "75.78,-75.78,-427.56,427.56".
Bounds string
// Registration is an aircraft registration.
Registration string
// AircraftType is an aircraft model code, e.g. "B737".
AircraftType string
// Details fetches the details of every flight found, MaxWorkers at a time.
Details bool
}
FlightSearch narrows the flights Client.GetFlights returns. See Client.SetFlightTrackerConfig for the rest of the options.
type FlightTrackerConfig ¶
type FlightTrackerConfig struct {
FAA string `json:"faa"`
Satellite string `json:"satellite"`
MLAT string `json:"mlat"`
FLARM string `json:"flarm"`
ADSB string `json:"adsb"`
GND string `json:"gnd"`
Air string `json:"air"`
Vehicles string `json:"vehicles"`
Estimated string `json:"estimated"`
MaxAge string `json:"maxage"`
Gliders string `json:"gliders"`
Stats string `json:"stats"`
Limit string `json:"limit"`
}
FlightTrackerConfig holds the settings of the Real Time Flight Tracker, used by Client.GetFlights. Every value is the string FR24 expects in the query.
func NewFlightTrackerConfig ¶
func NewFlightTrackerConfig() FlightTrackerConfig
NewFlightTrackerConfig returns the config FR24's own web player sends.
func (FlightTrackerConfig) Values ¶
func (c FlightTrackerConfig) Values() url.Values
Values renders the config as the query FR24's feed expects.
type LoginError ¶
type LoginError struct {
Message string
}
LoginError reports a failed login, or an authenticated endpoint reached without one.
func (*LoginError) Error ¶
func (e *LoginError) Error() string
func (*LoginError) Unwrap ¶
func (e *LoginError) Unwrap() error
type Options ¶
type Options struct {
// Timeout bounds a single request. Zero or less means [DefaultTimeout]; for
// a deadline of your own, cancel the context you pass to the call.
Timeout time.Duration
// MaxWorkers bounds the concurrent detail requests [Client.GetFlights]
// makes. Zero or less means 8.
MaxWorkers int
// Retry retries transient failures, including Cloudflare blocks. Nil means
// no retry. Build one with [NewRetryPolicy], which reports an unusable
// policy the way the Python and Node.js ports do.
Retry *RetryPolicy
// TLSProfile overrides the TLS handshake the client presents. Use it when
// FR24 updates its Cloudflare bot mitigation faster than this library
// releases. Nil means [Chrome136Profile].
TLSProfile *TLSProfile
// HTTPClient replaces the whole HTTP client, which is how a real TLS
// impersonation library (utls, tls-client) is plugged in. Set
// Transport.DisableCompression so this package owns content decoding and its
// size budget stays enforceable. Leave CheckRedirect unset, or the cookies
// FR24 hands out on a redirect hop are not banked. Any Jar is ignored: this
// package renders the Cookie header itself.
HTTPClient *http.Client
// contains filtered or unexported fields
}
Options configures a Client. Every field's zero value means the default, so Options{MaxWorkers: 4} changes only that one.
type Positioned ¶
type Positioned interface {
Position() (latitude, longitude *float64)
}
Positioned is anything with a location, so distances can be measured between an Airport and a Flight.
type Response ¶
type Response struct {
URL string
StatusCode int
Status string
Header http.Header
// Body is the body after Content-Encoding has been undone.
Body []byte
// Cookies are the name/value pairs the response set.
Cookies map[string]string
}
Response is a decoded FlightRadar24 response.
func (*Response) IsJSON ¶
IsJSON reports whether the response announced a JSON body. Compared in lower case, because a media type is case-insensitive.
type RetryPolicy ¶
type RetryPolicy struct {
// MaxAttempts is the total number of attempts, including the first. Below
// two, nothing is retried.
MaxAttempts int
// BaseDelay is the first backoff sleep. Zero or less means
// [DefaultRetryBaseDelay], so a struct literal backs off like
// [NewRetryPolicy] rather than hammering.
BaseDelay time.Duration
// MaxDelay caps the exponential backoff. Zero or less means
// [DefaultRetryMaxDelay]; for an effectively uncapped policy, set it high.
MaxDelay time.Duration
// Jitter is the random span added to each sleep. Zero means none, which is
// what a deterministic test wants.
Jitter time.Duration
}
RetryPolicy retries transient failures: a Cloudflare block, a timeout, or a network error. The zero value retries nothing.
func NewRetryPolicy ¶
func NewRetryPolicy(maxAttempts int) (*RetryPolicy, error)
NewRetryPolicy returns a policy with the usual exponential backoff: 1s base, 30s cap, 500ms jitter.
Example ¶
package main
import (
"context"
"errors"
"fmt"
"log"
"github.com/JeanExtreme002/FlightRadarAPI/go/flightradarapi"
)
func main() {
// Three attempts, with exponential backoff between them.
retry, err := flightradarapi.NewRetryPolicy(3)
if err != nil {
log.Fatal(err)
}
client := flightradarapi.New(flightradarapi.Options{Retry: retry})
_, err = client.GetMostTracked(context.Background())
// Every error of this package wraps a sentinel.
if errors.Is(err, flightradarapi.ErrCloudflare) {
fmt.Println("still blocked after three attempts")
}
}
Output:
func (*RetryPolicy) SleepFor ¶
func (p *RetryPolicy) SleepFor(attemptIndex int) time.Duration
SleepFor returns the backoff before the attempt after the given 0-based one.
Every field is public, so this must hold for values New never saw: a zero MaxDelay caps nothing rather than capping everything at zero, and a negative Jitter adds nothing rather than panicking.
type StatusError ¶
StatusError reports a status code the caller did not allow.
func (*StatusError) Error ¶
func (e *StatusError) Error() string
func (*StatusError) Unwrap ¶
func (e *StatusError) Unwrap() error
type TLSProfile ¶
type TLSProfile struct {
CipherSuites []uint16
CurvePreferences []tls.CurveID
MinVersion uint16
MaxVersion uint16
}
TLSProfile approximates a browser's TLS handshake. Go fixes its own cipher suite ordering, so this narrows the offered set and curve order rather than reproducing a JA3 exactly; see Options.HTTPClient for full impersonation.
func Chrome136Profile ¶
func Chrome136Profile() TLSProfile
Chrome136Profile is the TLS profile used by default.