countrycode

package
v1.147.1 Latest Latest
Warning

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

Go to latest
Published: Jul 11, 2026 License: MIT Imports: 5 Imported by: 0

Documentation

Overview

Package countrycode provides fast, reusable access to ISO-3166 country metadata.

It solves a common backend need: translating country identifiers into normalized, structured records and selecting countries by geographic hierarchy, assignment status, or top-level domain.

CountryData includes:

  • ISO-3166 alpha-2, alpha-3, and numeric codes
  • English and French country names
  • region, sub-region, and intermediate region names and codes
  • assignment status and top-level domain (TLD)

Data sources and initialization

New(nil) builds a Data instance from embedded defaults sourced from ISO-3166, the CIA World Factbook, United Nations M49, and Wikipedia. New also accepts a custom []CountryData dataset when applications need private overrides, curated subsets, or pinned metadata snapshots.

Top features

  • Direct lookup by Alpha-2, Alpha-3, Numeric code, and TLD.
  • Region/status enumerations through EnumRegion, EnumSubRegion, EnumIntermediateRegion, and EnumStatus.
  • Country list queries by region/sub-region/intermediate region, status, and TLD for filtering and reporting workflows.
  • Compact internal encoding optimized for quick lookups and low memory usage.

Why this matters

  • Standardizes country metadata handling across services and teams.
  • Reduces repeated parsing and mapping logic in validation/enrichment paths.
  • Keeps geographic lookups efficient for both request/response APIs and batch data pipelines.

Typical usage

Create a resolver with New, then retrieve a single country with CountryByAlpha2Code, CountryByAlpha3Code, or CountryByNumericCode, or fetch filtered sets using CountriesByRegionCode, CountriesByStatusName, and related query methods.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidCode is returned when a country, region, status, or TLD code is
	// malformed: it has the wrong length or contains characters outside the
	// expected range. It signals bad caller input (e.g. maps to HTTP 400).
	ErrInvalidCode = errors.New("countrycode: invalid code")

	// ErrNotFound is returned when a well-formed code or name matches no record
	// in the dataset. It signals a missing lookup target (e.g. maps to HTTP 404).
	ErrNotFound = errors.New("countrycode: not found")
)

Functions

This section is empty.

Types

type CountryData

type CountryData struct {
	StatusCode             uint8  `json:"statusCode"`
	Status                 string `json:"status"`
	Alpha2Code             string `json:"alpha2Code"`
	Alpha3Code             string `json:"alpha3Code"`
	NumericCode            string `json:"numericCode"`
	NameEnglish            string `json:"nameEnglish"`
	NameFrench             string `json:"nameFrench"`
	Region                 string `json:"region"`
	SubRegion              string `json:"subRegion"`
	IntermediateRegion     string `json:"intermediateRegion"`
	RegionCode             string `json:"regionCode"`
	SubRegionCode          string `json:"subRegionCode"`
	IntermediateRegionCode string `json:"intermediateRegionCode"`
	TLD                    string `json:"tld"`
}

CountryData contains the country data to be returned.

type Data

type Data struct {
	// contains filtered or unexported fields
}

Data contains the internal country Data and various indexes.

func New

func New(cdata []*CountryData) (*Data, error)

New builds a Data resolver with all lookup indexes precomputed.

If cdata is nil or empty, embedded default metadata is loaded; otherwise cdata is encoded and indexed. Reusing the returned Data instance avoids repeated index construction and keeps country lookups fast in hot paths.

The returned Data is read-only after construction and therefore safe for concurrent use by multiple goroutines.

When cdata contains multiple records sharing the same alpha-2 code, the last record silently overwrites the earlier ones in the lookup tables. The same last-wins resolution applies to duplicate alpha-3, numeric, and TLD codes.

Default data sources (updated at: 2024-07-17):

func (*Data) CountriesByIntermediateRegionCode

func (d *Data) CountriesByIntermediateRegionCode(code string) ([]*CountryData, error)

CountriesByIntermediateRegionCode returns countries in an intermediate-region code.

Example: "014" returns Eastern Africa. See EnumIntermediateRegion for valid codes.

func (*Data) CountriesByIntermediateRegionName

func (d *Data) CountriesByIntermediateRegionName(name string) ([]*CountryData, error)

CountriesByIntermediateRegionName returns countries in an intermediate-region name.

Example: "Eastern Africa". See EnumIntermediateRegion for valid names.

func (*Data) CountriesByRegionCode

func (d *Data) CountriesByRegionCode(code string) ([]*CountryData, error)

CountriesByRegionCode returns countries belonging to a region code.

Example: "150" returns Europe. See EnumRegion for valid codes.

func (*Data) CountriesByRegionName

func (d *Data) CountriesByRegionName(name string) ([]*CountryData, error)

CountriesByRegionName returns countries belonging to a region name.

Example: "Europe". See EnumRegion for valid names.

func (*Data) CountriesByStatusID

func (d *Data) CountriesByStatusID(id uint8) ([]*CountryData, error)

CountriesByStatusID returns countries that match an internal status ID.

See EnumStatus for status names and code values.

func (*Data) CountriesByStatusName

func (d *Data) CountriesByStatusName(name string) ([]*CountryData, error)

CountriesByStatusName returns countries that match a status name.

Example: "Officially assigned". See EnumStatus for valid names.

func (*Data) CountriesBySubRegionCode

func (d *Data) CountriesBySubRegionCode(code string) ([]*CountryData, error)

CountriesBySubRegionCode returns countries belonging to a sub-region code.

Example: "039" returns Southern Europe. See EnumSubRegion for valid codes.

func (*Data) CountriesBySubRegionName

func (d *Data) CountriesBySubRegionName(name string) ([]*CountryData, error)

CountriesBySubRegionName returns countries belonging to a sub-region name.

Example: "Southern Europe". See EnumSubRegion for valid names.

func (*Data) CountriesByTLD

func (d *Data) CountriesByTLD(tld string) ([]*CountryData, error)

CountriesByTLD returns countries associated with a top-level domain code.

Example: "it" resolves to Italy. This is useful for domain-based heuristics and enrichment pipelines.

func (*Data) CountryByAlpha2Code

func (d *Data) CountryByAlpha2Code(alpha2 string) (*CountryData, error)

CountryByAlpha2Code returns country metadata for an ISO-3166 alpha-2 code.

Example: "IT" resolves to Italy. This is the fastest lookup path when upstream systems already use alpha-2 identifiers.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/tecnickcom/nurago/pkg/countrycode"
)

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

	got, err := data.CountryByAlpha2Code("ZW")
	if err != nil {
		log.Fatal(err)
	}

	b, err := json.MarshalIndent(got, "", "  ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(b))

}
Output:
{
  "statusCode": 1,
  "status": "Officially assigned",
  "alpha2Code": "ZW",
  "alpha3Code": "ZWE",
  "numericCode": "716",
  "nameEnglish": "Zimbabwe",
  "nameFrench": "Zimbabwe (le)",
  "region": "Africa",
  "subRegion": "Sub-Saharan Africa",
  "intermediateRegion": "Eastern Africa",
  "regionCode": "002",
  "subRegionCode": "202",
  "intermediateRegionCode": "014",
  "tld": "zw"
}
Example (Export)
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/tecnickcom/nurago/pkg/countrycode"
)

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

	expCountries := make([]*countrycode.CountryData, 0, 26*26)

	// Generate all 2-letter country codes possible combinations, from AA to ZZ.
	for c1 := 'A'; c1 <= 'Z'; c1++ {
		for c0 := 'A'; c0 <= 'Z'; c0++ {
			alpha2 := string([]rune{c1, c0})

			// Decode country data from the 2-letter country code.
			country, err := data.CountryByAlpha2Code(alpha2)
			if err != nil {
				log.Fatal(err)
			}

			expCountries = append(expCountries, country)
		}
	}

	// Export the country data to JSON.
	jsonExpCountries, err := json.MarshalIndent(expCountries, "", "  ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(jsonExpCountries))
}

func (*Data) CountryByAlpha3Code

func (d *Data) CountryByAlpha3Code(alpha3 string) (*CountryData, error)

CountryByAlpha3Code returns country metadata for an ISO-3166 alpha-3 code.

Example: "ITA" resolves to Italy. The function bridges alpha-3 identifiers to the package's unified country record.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/tecnickcom/nurago/pkg/countrycode"
)

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

	got, err := data.CountryByAlpha3Code("ZWE")
	if err != nil {
		log.Fatal(err)
	}

	b, err := json.MarshalIndent(got, "", "  ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(b))

}
Output:
{
  "statusCode": 1,
  "status": "Officially assigned",
  "alpha2Code": "ZW",
  "alpha3Code": "ZWE",
  "numericCode": "716",
  "nameEnglish": "Zimbabwe",
  "nameFrench": "Zimbabwe (le)",
  "region": "Africa",
  "subRegion": "Sub-Saharan Africa",
  "intermediateRegion": "Eastern Africa",
  "regionCode": "002",
  "subRegionCode": "202",
  "intermediateRegionCode": "014",
  "tld": "zw"
}

func (*Data) CountryByNumericCode

func (d *Data) CountryByNumericCode(num string) (*CountryData, error)

CountryByNumericCode returns country metadata for an ISO-3166 numeric code.

Example: "380" resolves to Italy. This is useful when integrating with systems that store numeric ISO identifiers.

Example
package main

import (
	"encoding/json"
	"fmt"
	"log"

	"github.com/tecnickcom/nurago/pkg/countrycode"
)

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

	got, err := data.CountryByNumericCode("716")
	if err != nil {
		log.Fatal(err)
	}

	b, err := json.MarshalIndent(got, "", "  ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(b))

}
Output:
{
  "statusCode": 1,
  "status": "Officially assigned",
  "alpha2Code": "ZW",
  "alpha3Code": "ZWE",
  "numericCode": "716",
  "nameEnglish": "Zimbabwe",
  "nameFrench": "Zimbabwe (le)",
  "region": "Africa",
  "subRegion": "Sub-Saharan Africa",
  "intermediateRegion": "Eastern Africa",
  "regionCode": "002",
  "subRegionCode": "202",
  "intermediateRegionCode": "014",
  "tld": "zw"
}

func (*Data) EnumIntermediateRegion

func (d *Data) EnumIntermediateRegion() map[string]string

EnumIntermediateRegion returns all intermediate-region names mapped to their codes.

This supports finer-grained geographic grouping where region/sub-region are not specific enough.

func (*Data) EnumRegion

func (d *Data) EnumRegion() map[string]string

EnumRegion returns all region names mapped to their M49-style region codes.

It provides a canonical region catalog for filtering and reporting flows.

func (*Data) EnumStatus

func (d *Data) EnumStatus() map[string]string

EnumStatus returns all assignment-status names mapped to their numeric code strings.

This is useful for UI dropdowns, validation tables, and API metadata where callers need discoverable status values.

func (*Data) EnumSubRegion

func (d *Data) EnumSubRegion() map[string]string

EnumSubRegion returns all sub-region names mapped to their codes.

This gives callers a stable reference set for sub-region filtering.

type Names

type Names struct {
	EN string
	FR string
}

Names contains the English and French Names of a country.

Jump to

Keyboard shortcuts

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