countries

package module
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2025 License: MIT Imports: 6 Imported by: 0

README

Go REST Countries API Wrapper

Go Reference Go Report Card Go Version Static Badge

Go wrapper for the REST Countries API (API v3.1).

This small, dependency-light package provides typed access to https://restcountries.com/ (v3.1). It mirrors the API endpoints and returns a convenient Country struct for JSON responses.

Key features

  • Lightweight, idiomatic Go API around REST Countries v3.1
  • Typed Country model covering commonly used fields (name, codes, capital, currencies, flags, population, etc.)
  • Convenience functions for the most common endpoints: All, ByName, ByCode, ByCapital, ByRegion, and more

Installation

The module path is github.com/supcik/go-countries. To add it to your project use Go modules:

go get github.com/supcik/go-countries@latest

or import it directly in your code and run go mod tidy:

import "github.com/supcik/go-countries"

Quick example

Create a small main.go to fetch a country by ISO code and print its capital:

package main

import (
	"fmt"
	"log"

	"github.com/supcik/go-countries"
)

func main() {
	// ByCode returns a single Country for an ISO code like "CH" or "FRA"
	c, err := countries.ByCode("CH", "name", "capital", "cca2", "population")
	if err != nil {
		log.Fatalf("failed to fetch country: %v", err)
	}

	fmt.Printf("Country: %s\n", c.Name.Common)
	if len(c.Capital) > 0 {
		fmt.Printf("Capital: %s\n", c.Capital[0])
	}
	fmt.Printf("Population: %d\n", c.Population)
}

Notes about fields

The REST Countries API supports a fields query parameter to limit the returned fields (and reduce payload). This wrapper mirrors that behaviour: most functions accept a variadic fields ...string parameter. When calling All() you must specify the fields you need (the underlying API rejects requests that do not include a fields filter when returning all countries). Example fields: name, cca2, capital, currencies, flags, population.

Examples

  • Get all countries with only name and cca2:
countries.All("name", "cca2")
  • Search by name (partial match):
countries.ByName("united", "name", "cca3", "capital")
  • Exact full name match:
countries.ByFullName("United Kingdom of Great Britain and Northern Ireland", "name", "capital")
  • Multiple codes in one request:
codes := []string{"CH", "DE", "FR"}
countries.ByCodes(codes, "name", "capital")

Contributing

Contributions are welcome. Open an issue for bugs or feature requests and submit PRs for fixes or improvements. Keep changes small and focused and include tests where appropriate.

License

This project is licensed under the MIT License — see LICENSE.txt for details.

Acknowledgements and references

  • REST Countries: https://restcountries.com/
  • Related libraries (for reference):
    • github.com/chriscross0/go-restcountries/v2
    • github.com/joaomlopes/gocountries
    • github.com/alediaferia/gocountries

Contact

Maintainer: Jacques Supcik — jacques.supcik@hefr.ch

Documentation

Index

Examples

Constants

View Source
const ApiVersion = "v3.1"
View Source
const BaseUrl = "https://restcountries.com/" + ApiVersion + "/"

Variables

This section is empty.

Functions

This section is empty.

Types

type CapitalInfo

type CapitalInfo struct {
	Latlng []float64 `json:"latlng"` // Capital latitude and longitude
}

CapitalInfo represents the capital information, specifically the latitude and longitude coordinates.

type Car

type Car struct {
	Signs []string `json:"signs"` // Car distinguished (oval) signs
	Side  string   `json:"side"`  // Car driving side
}

Car represents the driving side and distinguished (oval) signs of a country.

type Country

type Country struct {
	Name         Name                `json:"name"`
	Tld          []string            `json:"tld"`          // Internet top level domains
	Cca2         string              `json:"cca2"`         // ISO 3166-1 alpha-2 two-letter country codes
	Ccn3         string              `json:"ccn3"`         // ISO 3166-1 numeric code (UN M49)
	Cca3         string              `json:"cca3"`         // ISO 3166-1 alpha-3 three-letter country codes
	Cioc         string              `json:"cioc"`         // Code of the International Olympic Committee
	Fifa         string              `json:"fifa"`         // FIFA code
	Independent  bool                `json:"independent"`  // ISO 3166-1 independence status (the country is considered a sovereign state)
	Status       string              `json:"status"`       // ISO 3166-1 assignment status
	UnMember     bool                `json:"unMember"`     // UN Member status
	Currencies   map[string]Currency `json:"currencies"`   // List of all currencies
	Idd          Idd                 `json:"idd"`          // International dialing codes
	Capital      []string            `json:"capital"`      // Capital cities
	CapitalInfo  CapitalInfo         `json:"capitalInfo"`  // Capital latitude and longitude
	AltSpellings []string            `json:"altSpellings"` // Alternate spellings of the country name
	Region       string              `json:"region"`       // UN demographic regions
	Subregion    string              `json:"subregion"`    // UN demographic subregions
	Continents   []string            `json:"continents"`   // List of continents the country is on
	Languages    map[string]string   `json:"languages"`    // List of official language
	Translations map[string]Name     `json:"translations"` // List of country name translations
	Latlng       []float64           `json:"latlng"`       // Latitude and longitude
	Landlocked   bool                `json:"landlocked"`   // Landlocked country
	Borders      []string            `json:"borders"`      // Border countries
	Area         float64             `json:"area"`         // Geographical size
	Demonyms     Demonyms            `json:"demonyms"`     // Inhabitants of the country
	Flag         string              `json:"flag"`         // flag emoji
	Flags        map[string]string   `json:"flags"`        // Flagpedia links to svg and png flags
	CoatOfArms   map[string]string   `json:"coatOfArms"`   // MainFacts.com links to svg and png images
	Population   int                 `json:"population"`   // Country population
	Maps         map[string]string   `json:"maps"`         // Link to Google maps and Open Street maps
	Gini         map[string]float64  `json:"gini"`         // Worldbank Gini index
	Car          Car                 `json:"car"`          // Car driving side and distinguished (oval) signs
	PostalCode   PostalCode          `json:"postalCode"`   // Country postal codes
	StartOfWeek  string              `json:"startOfWeek"`  // Day of the start of week (Sunday/Monday/Saturday)
	Timezones    []string            `json:"timezones"`    // Timezones
}

Country represents the main structure for a country, including various details such as name, codes, currencies, languages, and more.

func All

func All(fields ...string) ([]Country, error)

All retrieves data for all countries. You must specify the fields you need (up to 10 fields) when calling this method, otherwise you'll get an error.

func ByCapital

func ByCapital(capital string, fields ...string) ([]Country, error)

ByCapital retrieves data for countries with the given capital city.

func ByCode

func ByCode(code string, fields ...string) (Country, error)

ByCode retrieves data for the country matching the given country code. You can use either cca2 (ISO 3166-1 alpha-2) ccn3 (ISO 3166-1 numeric), cca3 (ISO 3166-1 alpha-3) or cioc (International Olympic Committee)

func ByCodes

func ByCodes(codes []string, fields ...string) ([]Country, error)

ByCodes retrieves data for multiple countries matching the given country codes. You can use the same codes as in ByCode function. The codes should be provided as a slice of strings.

func ByCurrency

func ByCurrency(currency string, fields ...string) ([]Country, error)

ByCurrency retrieves data for countries using the given currency code or name.

func ByDemonym

func ByDemonym(demonym string, fields ...string) ([]Country, error)

ByDemonym retrieves data for countries matching how a citizen is called.

func ByFullName

func ByFullName(name string, fields ...string) ([]Country, error)

ByFullName retrieves data for countries matching the exact full name. It can be the common or official name.

func ByIndependence

func ByIndependence(independent bool, fields ...string) ([]Country, error)

ByIndependence retrieves data for countries based on their independence status.

func ByLanguage

func ByLanguage(language string, fields ...string) ([]Country, error)

ByLanguage retrieves data for countries where the given language code or name is spoken.

func ByName

func ByName(name string, fields ...string) ([]Country, error)

ByName retrieves data for countries matching the given name. It can be the common or official name. If you want to get an exact match, use the ByFullName function.

Example
countries, err := countries.ByName("Switzerland", "name", "capital", "region")
if err != nil {
	panic(err)
}
for _, country := range countries {
	fmt.Printf("The capital of %s (%s) is %s.\n", country.Name.Common, country.Region, country.Capital[0])
}
Output:
The capital of Switzerland (Europe) is Bern.

func ByRegion

func ByRegion(region string, fields ...string) ([]Country, error)

ByRegion retrieves data for countries in the given region (e.g. Europe) Currently available regions are: Africa, Americas, Antarctic, Asia, Europe and Oceania.

func BySubregion

func BySubregion(subregion string, fields ...string) ([]Country, error)

BySubregion retrieves data for countries in the given subregion (e.g. Western Europe)

func ByTranslation

func ByTranslation(translation string, fields ...string) ([]Country, error)

ByTranslation retrieves data for countries matching the given translation of the country name.

type Currency

type Currency struct {
	Name   string `json:"name"`   // Currency name
	Symbol string `json:"symbol"` // Currency symbol
}

Currency represents the currency structure with its name and symbol.

type Demonyms

type Demonyms struct {
	F string `json:"f"` // Female demonym
	M string `json:"m"` // Male demonym
}

Demonyms represents the name of the inhabitants, with separate fields for male and female forms.

type ErrorMessage

type ErrorMessage struct {
	Message string `json:"message"`
	Status  int    `json:"status"`
}

type Idd

type Idd struct {
	Root     string   `json:"root"`     // International direct dialing root
	Suffixes []string `json:"suffixes"` // International direct dialing suffixes
}

Idd represents the international direct dialing information, including the root and suffixes.

type Name

type Name struct {
	NativeNameT
	NativeName map[string]NativeNameT `json:"nativeName"` // Native country name
}

Name represents the name structure. It includes the native names, and a map of native names in different languages.

type NativeNameT

type NativeNameT struct {
	Official string `json:"official"` // Official  country name
	Common   string `json:"common"`   // Common country name
}

NativeNameT represents the native name structure

type PostalCode

type PostalCode struct {
	Format string `json:"format"` // Postal code format
	Regex  string `json:"regex"`  // Postal code regex pattern
}

PostalCode represents the postal code format and regex pattern.

Jump to

Keyboard shortcuts

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