gogeo

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: Apache-2.0 Imports: 6 Imported by: 5

README

gogeo

Test Lint Go Report Card Go Reference

Static country, continent, and ISO 3166-2 region data with O(1) country lookups, packed region tables, and CountryCode2 / CountryID / RegionCode types for JSON and SQL.

License: Apache 2.0

Install

go get github.com/geniusrabbit/gogeo

Requires Go 1.21+.

Usage

Unknown ISO codes resolve to the undefined country (** / ***), never nil.

package main

import (
    "fmt"

    "github.com/geniusrabbit/gogeo"
)

func main() {
    us := gogeo.CountryByCode2("US")
    fmt.Println(us.Name, us.ISO3(), us.Continent(), us.Currency())

    // ISO-2 or ISO-3 → CountryCode2 or CountryID
    cc := gogeo.CountryCode2ByString("USA")
    fmt.Println(cc.ISO2(), cc.ISO3(), cc.Object().Name) // US USA United States

    id := gogeo.CountryIDByString("GB")
    fmt.Println(id.ISO2(), id.Code()) // GB GB

    // Zero-alloc lookup when you already have CountryCode2
    _ = gogeo.CountryByCode2Bytes(gogeo.CountryCode2{'D', 'E'})

    eu := gogeo.ContinentByCode2("EU")
    fmt.Println(eu.Name)

    ca := gogeo.RegionByCode("US-CA")
    fmt.Println(ca.Name, ca.Type(), ca.Country().Name) // California State United States
    fmt.Println(ca.UTCOffset)                          // -480, standard minutes east of UTC

    // UK is an alias; the country code is GB
    eng := gogeo.RegionByCode("UK-ENG")
    fmt.Println(eng.Code(), eng.Name) // GB-ENG England

    near := gogeo.RegionByLatLng(42.51, 1.52)
    fmt.Println(near.Code(), near.Name)

    _ = us.NearestRegion(34.05, -118.25)
}

CountryCode2, CountryID, and RegionCode implement json.Marshaler / Unmarshaler, driver.Valuer, and sql.Scanner. CountryID is the country index in memory; JSON and SQL still store the ISO-2 string, same as CountryCode2.

type User struct {
    Country   gogeo.CountryCode2 `json:"country" db:"country_code"`
    CountryID gogeo.CountryID    `json:"country_id" db:"country_id"`
    Region    gogeo.RegionCode   `json:"region" db:"region_code"`
}

Lists on Country are methods over packed tables: Currency(), Languages(), Phones(), TimeZones(), Regions(). TimeZone.UTCOffset and Region.UTCOffset are standard-time minutes east of UTC (not the current DST offset). Country.AvgUTCOffset is the rounded mean of that country's zones.

The dataset includes GeoIP-style extras (A1, A2, O1, AP, EU). The United Kingdom country code is GB; UK is an accepted alias for country and region lookup. ISO 3166-2 codes stay official (GB-ENG); RegionByCode accepts both GB-* and UK-*, and both hyphenated and compact forms (NL-ZH and NLZH).

Subdivision data is merged from Debian iso-codes (LGPL-2.1-or-later) and oodavid/iso-3166-2 centroids. See data/NOTICE and data/regions.json. Region.Name is English when available.

Development

Country and region tables are generated from data/countries.json and merged data/regions.json:

make build-data   # or: make generate
Target Description
make test Unit tests
make lint go vet + golangci-lint
make fmt Format sources
make merge-data Merge debian + oodavid into data/regions.json
make build-data Merge sources and regenerate Go tables
make export-data Dump countries or regions (KIND=countries|regions FORMAT=json|csv)
make bench Benchmarks
make cover Coverage report
make tidy go mod tidy
make clean Remove coverage artifacts

Benchmarks

make bench on darwin/arm64 (Apple M2 Ultra):

BenchmarkCountryByCode2-24               1.967 ns/op    0 B/op    0 allocs/op
BenchmarkCountryByCode2Bytes-24          1.892 ns/op    0 B/op    0 allocs/op
BenchmarkCountryByCode3-24               2.175 ns/op    0 B/op    0 allocs/op
BenchmarkCountryCode2ByStringISO2-24     2.682 ns/op    0 B/op    0 allocs/op
BenchmarkCountryCode2ByStringISO3-24     2.937 ns/op    0 B/op    0 allocs/op
BenchmarkCountryCodeISO2-24              2.315 ns/op    0 B/op    0 allocs/op
BenchmarkCountryCodeISO3-24              2.103 ns/op    0 B/op    0 allocs/op
BenchmarkCountryCodeMarshalJSON-24       4.318 ns/op    4 B/op    1 allocs/op
BenchmarkCountryCodeValue-24             2.348 ns/op    0 B/op    0 allocs/op

Documentation

Overview

Code generated by internal/cmd/gencountries from data/countries.json. DO NOT EDIT.

Code generated by internal/cmd/genregions from data/regions.json. DO NOT EDIT.

Index

Constants

View Source
const (
	UndefinedCountryCodeISO2 = "**"
	UndefinedCountryCodeISO3 = "***"
)

undefined country codes

View Source
const UndefinedRegionISO3166 = "**-**"

Undefined ISO 3166-2 code.

Variables

View Source
var (
	ErrCode2InvalidScanType  = errors.New("[gogeo.code2] invalid scan type, supports only bytes and string")
	ErrCode2InvalidValueSize = errors.New("[gogeo.code2] invalid value size, supports only two 2 chars")
)

Error list...

View Source
var (
	ErrCountryIDInvalidScanType  = errors.New("[gogeo.countryid] invalid scan type, supports only bytes and string")
	ErrCountryIDInvalidValueSize = errors.New("[gogeo.countryid] invalid value size, supports only two 2 chars")
)

Error list for CountryID SQL scanning.

View Source
var Continents = []Continent{
	{ID: 1, Code2: "EU", Name: "Europe"},
	{ID: 2, Code2: "AS", Name: "Asia"},
	{ID: 3, Code2: "AF", Name: "Africa"},
	{ID: 4, Code2: "OC", Name: "Oceania"},
	{ID: 5, Code2: "SA", Name: "South America"},
	{ID: 6, Code2: "NA", Name: "North America"},
	{ID: 7, Code2: "AN", Name: "Antarctica"},
}

Continents list (IDs are 1-based; Country.continent stores this ID).

View Source
var Countries = countries[:]

Countries is the public list of all countries. Index equals Country.ID.

View Source
var (
	ErrRegionCodeInvalidScanType = errors.New("[gogeo.region] invalid scan type, supports only bytes and string")
)

Error list for RegionCode SQL scanning.

View Source
var Regions = regions[:]

Regions is the public list of all subdivisions. Index equals Region.ID.

UndefinedCountryCode2 for undefined codename

View Source
var UndefinedRegionCode = RegionCode(0)

UndefinedRegionCode is the sentinel ISO 3166-2 code.

Functions

This section is empty.

Types

type Continent

type Continent struct {
	ID    uint8
	Code2 string
	Name  string
}

Continent description

func ContinentByCode2

func ContinentByCode2(code string) *Continent

ContinentByCode2 returns a continent by ISO-like 2-letter code, or nil.

type Coordinates

type Coordinates struct {
	Lat, Lon float32
}

Coordinates object

type Country

type Country struct {
	ID           uint8
	Code2        CountryCode2
	Name         string
	Native       string
	Capital      string
	Coordinates  Coordinates
	AvgUTCOffset int16
	// contains filtered or unexported fields
}

Country is a compact country record. Variable-length lists are stored in package-level packed tables and exposed via methods.

func CountryByCode2

func CountryByCode2(code string) *Country

CountryByCode2 returns the country for an ISO-2 code. Unknown codes resolve to the undefined country (never nil).

func CountryByCode2Bytes

func CountryByCode2Bytes(code CountryCode2) *Country

CountryByCode2Bytes is the allocation-free ISO-2 lookup. Unknown codes resolve to the undefined country (never nil).

func CountryByCode3

func CountryByCode3(code string) *Country

CountryByCode3 returns the country for an ISO-3 code. Empty and unknown codes resolve to the undefined country (never nil).

func CountryByID

func CountryByID(id uint8) *Country

CountryByID returns the country with the given ID, or the undefined country.

func (*Country) Code3

func (c *Country) Code3() string

Code3 returns the interned ISO-3166 alpha-3 code.

func (*Country) Continent

func (c *Country) Continent() string

Continent returns the interned continent code (EU, AS, ...) or empty.

func (*Country) Currency

func (c *Country) Currency() []string

Currency returns the packed currency codes for the country.

func (*Country) ISO2

func (c *Country) ISO2() string

ISO2 returns the interned ISO-3166 alpha-2 code.

func (*Country) ISO3

func (c *Country) ISO3() string

ISO3 returns the interned ISO-3166 alpha-3 code (empty if the entry has none).

func (*Country) Languages

func (c *Country) Languages() []string

Languages returns the packed language codes for the country.

func (Country) MarshalJSON

func (c Country) MarshalJSON() ([]byte, error)

MarshalJSON encodes Country using the historical field names.

func (*Country) NearestRegion

func (c *Country) NearestRegion(lat, lng float32) *Region

NearestRegion returns the nearest subdivision of this country, or undefined.

func (*Country) Phones

func (c *Country) Phones() []string

Phones returns the packed phone prefixes for the country.

func (*Country) Regions

func (c *Country) Regions() []Region

Regions returns ISO 3166-2 subdivisions for the country.

func (*Country) TimeZones

func (c *Country) TimeZones() []TimeZone

TimeZones returns the packed timezone list for the country.

type CountryCode2 added in v1.1.0

type CountryCode2 [2]byte

CountryCode2 implements a 2-letter country code.

func CountryCode2ByString

func CountryCode2ByString(code string) CountryCode2

CountryCode2ByString returns code by string code ISO-2 or ISO-3.

func (CountryCode2) ID added in v1.1.1

func (cc CountryCode2) ID() uint8

ID returns the interned country code, or 0 for undefined.

func (CountryCode2) ISO2 added in v1.1.0

func (cc CountryCode2) ISO2() string

ISO2 returns the interned two-letter code for a known country, or "**". Aliases resolve to the canonical code (UK → GB).

func (CountryCode2) ISO3 added in v1.1.0

func (cc CountryCode2) ISO3() string

ISO3 returns the interned three-letter code for the matching country.

func (CountryCode2) MarshalJSON added in v1.1.0

func (cc CountryCode2) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler interface

func (CountryCode2) Object added in v1.2.0

func (cc CountryCode2) Object() *Country

Object returns the country for this code, or the undefined country. UK resolves to GB. Never nil.

func (*CountryCode2) Scan added in v1.1.0

func (cc *CountryCode2) Scan(data interface{}) error

Scan implementation of sql.Scanner interface

func (CountryCode2) String added in v1.1.0

func (cc CountryCode2) String() string

func (*CountryCode2) UnmarshalJSON added in v1.1.0

func (cc *CountryCode2) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler interface

func (CountryCode2) Value added in v1.1.0

func (cc CountryCode2) Value() (driver.Value, error)

Value implementation of sql driver.Valuer interface

type CountryID added in v1.3.0

type CountryID uint8

CountryID is a country index for JSON and SQL fields. On the wire it is the ISO-2 code, same as CountryCode2.

var UndefinedCountryID CountryID

UndefinedCountryID is the sentinel country index.

func CountryIDByString added in v1.3.0

func CountryIDByString(code string) CountryID

CountryIDByString parses an ISO-2 or ISO-3 code. Unknown values become undefined.

func (CountryID) Code added in v1.3.0

func (id CountryID) Code() CountryCode2

Code returns the canonical ISO-2 code. UK resolves to GB.

func (CountryID) ID added in v1.3.0

func (id CountryID) ID() uint8

ID returns the interned country index, or 0 for undefined.

func (CountryID) ISO2 added in v1.3.0

func (id CountryID) ISO2() string

ISO2 returns the interned two-letter code, or "**".

func (CountryID) ISO3 added in v1.3.0

func (id CountryID) ISO3() string

ISO3 returns the interned three-letter code for the matching country.

func (CountryID) MarshalJSON added in v1.3.0

func (id CountryID) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (CountryID) Object added in v1.3.0

func (id CountryID) Object() *Country

Object returns the country for this index, or the undefined country. Never nil.

func (*CountryID) Scan added in v1.3.0

func (id *CountryID) Scan(data interface{}) error

Scan implementation of sql.Scanner.

func (CountryID) String added in v1.3.0

func (id CountryID) String() string

func (*CountryID) UnmarshalJSON added in v1.3.0

func (id *CountryID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (CountryID) Value added in v1.3.0

func (id CountryID) Value() (driver.Value, error)

Value implementation of sql driver.Valuer.

type Region

type Region struct {
	ID          uint16
	Name        string
	Coordinates Coordinates
	UTCOffset   int16
	// contains filtered or unexported fields
}

Region is a compact ISO 3166-2 subdivision record.

func RegionByCode

func RegionByCode(code string) *Region

RegionByCode returns the region for an ISO 3166-2 code (for example "US-CA"). Hyphenated and compact forms are equivalent ("NL-ZH" and "NLZH"). "GB-*" and "UK-*" resolve to the same United Kingdom subdivisions (country code GB). Unknown codes resolve to the undefined region (never nil).

func RegionByID

func RegionByID(id uint16) *Region

RegionByID returns the region with the given ID, or the undefined region.

func RegionByLatLng

func RegionByLatLng(lat, lng float32) *Region

RegionByLatLng returns the nearest region with coordinates, or undefined.

func (*Region) Code

func (r *Region) Code() string

Code returns the interned ISO 3166-2 code (for example "US-CA").

func (*Region) Country

func (r *Region) Country() *Country

Country returns the parent country. GB subdivisions resolve to GB. Never nil.

func (*Region) HasCoordinates

func (r *Region) HasCoordinates() bool

HasCoordinates reports whether the region has a known centroid.

func (*Region) Names

func (r *Region) Names() []string

Names returns the default name first, then unique alternatives.

func (*Region) Parent

func (r *Region) Parent() *Region

Parent returns the parent subdivision, or nil if the region is top-level.

func (*Region) RegionCode

func (r *Region) RegionCode() RegionCode

RegionCode returns the JSON/SQL code wrapper for this region.

func (*Region) Type

func (r *Region) Type() string

Type returns the interned subdivision type (State, Province, Parish, ...).

type RegionCode

type RegionCode uint16

RegionCode is an ISO 3166-2 subdivision code for JSON and SQL fields.

func RegionCodeByString

func RegionCodeByString(code string) RegionCode

RegionCodeByString parses an ISO 3166-2 code. Unknown values become undefined.

func (RegionCode) Country

func (rc RegionCode) Country() CountryCode2

Country returns the library country code (GB subdivisions → GB).

func (RegionCode) ISO3166

func (rc RegionCode) ISO3166() string

ISO3166 returns the interned ISO 3166-2 code, or "**-**".

func (RegionCode) MarshalJSON

func (rc RegionCode) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (RegionCode) Region

func (rc RegionCode) Region() *Region

Region returns the matching region (never nil).

func (*RegionCode) Scan

func (rc *RegionCode) Scan(data interface{}) error

Scan implementation of sql.Scanner.

func (RegionCode) String

func (rc RegionCode) String() string

func (*RegionCode) UnmarshalJSON

func (rc *RegionCode) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (RegionCode) Value

func (rc RegionCode) Value() (driver.Value, error)

Value implementation of sql driver.Valuer.

type TimeZone

type TimeZone struct {
	ZoneName  string
	Lon       float32
	UTCOffset int16
}

TimeZone object. UTCOffset is minutes east of UTC in standard time.

Directories

Path Synopsis
internal
cmd/export command
Command export dumps gogeo countries or ISO 3166-2 regions as JSON or CSV.
Command export dumps gogeo countries or ISO 3166-2 regions as JSON or CSV.
cmd/gencountries command
Command gencountries builds packed country tables from data/countries.json.
Command gencountries builds packed country tables from data/countries.json.
cmd/genregions command
Command genregions builds packed ISO 3166-2 tables from data/regions.json.
Command genregions builds packed ISO 3166-2 tables from data/regions.json.
cmd/mergerregions command
Command mergerregions merges Debian iso-codes and oodavid/iso-3166-2 into data/regions.json.
Command mergerregions merges Debian iso-codes and oodavid/iso-3166-2 into data/regions.json.
utcoffset
Package utcoffset resolves a stable standard-time UTC offset for an IANA zone.
Package utcoffset resolves a stable standard-time UTC offset for an IANA zone.

Jump to

Keyboard shortcuts

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