Gountries provides: Countries (ISO-3166-1), Country Subdivisions(ISO-3166-2), Currencies (ISO 4217), Geo Coordinates(ISO-6709) as well as translations, country borders and other stuff exposed as struct data.

Overview

gountries

wercker status codecov.io Go Report Card

Inspired by the countries gem for ruby.

Countries (ISO-3166-1), Country Subdivisions(ISO-3166-2), Currencies (ISO 4217), Geo Coordinates(ISO-6709) as well as translations, country borders and other stuff exposed as struct data.

All data is derived from the pariz/countries repo.

This is currently a work in progress, so things may change. More stuff will be added

Installation

go get github.com/pariz/gountries

Examples

Basic

import (
  "github.com/pariz/gountries"
  "fmt"
)


query := gountries.New()

/////////////////
// Find sweden //
/////////////////

sweden, _ := query.FindCountryByName("sweden")
// sweden, _ := query.FindCountryByAlpha("SE")
// sweden, _ := query.FindCountryByAlpha("SWE")

fmt.Println(sweden.Name.Common) // Output: Sweden
fmt.Println(sweden.Name.Official) // Output: Konungariket Sverige

fmt.Println(sweden.Translations["DEU"].Common) // Output: Schweden
fmt.Println(sweden.Translations["DEU"].Official) // Output: Königreich Schweden

A bit more advanced

import (
  "github.com/pariz/gountries"
  "fmt"
)

query := gountries.New()

////////////////////////////////////////////
// Find the bordering countries of Sweden //
////////////////////////////////////////////

sweden, _ := query.FindCountryByAlpha("SWE") // "SE" also works..

// Get the bordering countries of sweden
for _, country := range sweden.BorderingCountries() {
	fmt.Println(country.Name.Common)
}

// Output:
// Finland
// Norway

////////////////////////////////////
// Find all subdivisons for Sweden //
////////////////////////////////////

subdivisions := sweden.SubDivisions()

for _, subdivision := range subdivisions {
	fmt.Println(subdivision.Name)
}

// Output:
// Västerbottens län
// Uppsala län
// Södermanlands län
// Gotlands län
// Dalarnas län
// ...

//////////////////////////////////////////////////////////
// Find all countries bordering Germany and Switzerland //
//////////////////////////////////////////////////////////

countryQuery := Country{
	Borders: []string{
		"DEU",
		"CHE",
	},
}

countries := query.FindCountries(countryQuery)

for _, c := range countries {
	fmt.Println(c.Name.Common)
}

// Output:
// Austria
// France

///////////////////////////////////////////////////////////////////
// Calculate distance between Sweden and Germany (in Kilometers) //
///////////////////////////////////////////////////////////////////

se, _ := query.FindCountryByAlpha("SWE")
de, _ := query.FindCountryByAlpha("DEU")

distance := gountries.MeasureDistanceHaversine(se, de)
//distance := MeasureDistancePythagoras(se, de)

fmt.Println(distance)

// Output:
// 1430.1937864547901

distance = gountries.CalculateHaversine(
	se.Coordinates.MaxLatitude, se.Coordinates.MaxLongitude,
	de.Coordinates.MinLatitude, de.Coordinates.MinLongitude)

fmt.Println(distance)

// Output:
// 2641.26145088825

Using packed data

The data in the data/yaml subdirectory is embedded using go-bindata. Once you include this library in your project, you won't need to access the data directory. To add or update the data, make changes to the YAML files then run:

go-bindata -pkg gountries data/yaml/*

Testing

Has a pretty solid test coverage but is constantly improving.

Todo

  • Province/County querying (partially complete)
  • Measurement between coordinates
  • GeoJSON information
  • Suggestions?
Issues
  • Including translated names in NameToAlpha2

    Including translated names in NameToAlpha2

    Would you be willing to accept a PR that adds translated country names to NameToAlpha2? I've run into several cases where lookups by name have failed but the spelling variant is among the translations.

    opened by oschwald 3
  • Embed data using go-bindata and use bi-directional map to speed up lookups

    Embed data using go-bindata and use bi-directional map to speed up lookups

    I'm planning on using your library as part of an API and I was going to make a few changes to get faster lookups and embed the data directly into the binary to make it easier to deploy. Interested in a pull request?

    Planned features:

    1. Embed the country data from the YAML files using go-bindata so that the deployment remains a single binary without relying on an external data directory. This would be backwards compatible so that when you populateCountries or populateSubdivisions it checks the bindata first and then falls back to the data directory.
    2. Use a bidirectional tree map from the gods library so that lookups by either country name or alpha code are more efficient.
    3. Support returning either all of the data or a particular subset of countries as a struct that is easily marshaled to JSON. This is useful to populate a frontend web UI for entering billing/shipping addresses.

    This could simplify some of the query functions by using the tree to do lookups, rather than looping through all of the available data.

    I'm going to fork your library and work on this a little bit. Let me know if you have any other ideas.

    opened by BTBurke 3
  • Issues with data directory

    Issues with data directory

    I faced with 2 issues

    • go get doesn't fetch content of data directory so it's empty after obtaining a project
    • example code fails with panic panic: Error loading Countries because it expects current directory of executable to contain data directory. But it's actually not there but inside github.com/pariz/gountries
    opened by pyeremenko 3
  • Calling New() concurrently creates data race because of concurrent access to queryInstance global variable

    Calling New() concurrently creates data race because of concurrent access to queryInstance global variable

    I think, we should get rid of global instances at all

    q1 := gountries.NewFromPath('path1') 
    q2 := gountries.NewFromPath('path2') // SURPRISE! q2 actually is q1
    
    opened by drscre 2
  • Add FindCountryByNativeName to take advantage of the available info

    Add FindCountryByNativeName to take advantage of the available info

    • Adding new map with pre processed native names to country alpha2 for quick lookup

    • Followed pattern used for other tests to cover additions/changes

    • Modified SX (Sint Maarten) data, as the Dutch section does not have FR as an official language, this is to prevent collision of native names when building the map (see MF, which contains the french native name)

    More info: https://en.wikipedia.org/wiki/Sint_Maarten#Languages

    opened by pnfb 2
  • BQ & SH country support

    BQ & SH country support

    Adressing #23 I noticed Carribean Netherlands (BQ) & Saint Helena (SH) country definitions were missing from the library, so I added country and subdivisions files for the two & generated the updated bindata.go

    opened by Youhar 2
  • Country methods re-parse the data every time they are used.

    Country methods re-parse the data every time they are used.

    This makes the library pretty unsuitable for use in real-world applications. Currently, in order to get, e.g., a Country's list of Subdivisions, it creates a new Query every time you call it. This is horribly inefficient.

    Probably the best way to solve this is make one Query and either make it a global variable that is initialized during package initialization, or allow it to be explicitly initialized if that isn't acceptable.

    enhancement 
    opened by alercah 2
  • Packed data and query speedups

    Packed data and query speedups

    This pull request packs the YAML data into bindata.go and relies on that first before falling back to the data directory. It also implements a couple of simple indexes to speed up the queries.

    I only implemented two of the things I outlined in ref #5. go-bindata is used to pack the YAML files. This makes it so the library can be embedded in any binary without needing access to the data/ directory. I updated the readme with instructions for how to repack the data if there are changes to the YAML files.

    The countries are now represented as a map[string]Country by Alpha2 key. Then a couple of simple indexes from common name -> alpha2 and alpha2 -> alpha3 are generated at the same time the query is initialized. This provides a pretty significant speed up:

    No query optimizations
    ===
    BenchmarkCountryLookupByName-4         10000        136806 ns/op
    PASS
    
    Indexed query
    ===
    BenchmarkCountryLookupByName-4       2000000           882 ns/op
    PASS
    

    All the tests pass. I added one simple query benchmark for looking up a country by name. I also added a sort to a couple of the tests to ensure that the test output comes out in a predictable order.

    opened by BTBurke 2
  • Add FindCountriesByCurrency

    Add FindCountriesByCurrency

    • Adding new map with pre-processed currency names to countries alpha2 for quick lookup
    • Followed pattern used for other tests to cover additions/changes
    opened by perriea 1
  • FindCountryByName does not support official names

    FindCountryByName does not support official names

    gountries.New().FindCountryByName("United States of America") 
    

    does not return a country where this does

    gountries.New().FindCountryByName("United States") 
    

    "United States of America" should be valid based on https://github.com/pariz/gountries/blob/9f809e356e5cc61e570a77e6b7fe5f5eafab3576/data/yaml/countries/us.yaml#L3

    name:
      common: United States
      official: United States of America
    

    Please extend this method to include official and native text.

    Thank you!

    opened by aaronmcohen 1
  • Country methods are inconsistent in receivers

    Country methods are inconsistent in receivers

    The methods for countries sometimes take pointer receivers, and sometimes take struct receivers. They should be made consistent. My preference would be to use pointers everywhere in this library, because the data structures are frequently large and shouldn't be needlessly copied.

    enhancement 
    opened by alercah 1
  • Error handling

    Error handling

    Hello!

    Would it be possible to either:

    • Remove the error formatting which introduces the gountries error part or
    • Make it customizable ?

    Sometimes we want to return the error from gountries to expose what's wrong to the API user, but the gountries part can create confusion as to what's wrong.

    Thanks!

    opened by adrianlungu 0
  • Some countries missing trailing

    Some countries missing trailing "(the)" in short name lower case

    Some countries have a trailing "(the)" in the ISO short name - for example, the USA: https://www.iso.org/obp/ui/#iso:code:3166:US screenshot-prp60

    When gountries is missing this, it causes validations to fail. Could these please be added, potentially behind a feature toggle?

    opened by egeland 0
  • Question marks in subdivision names (

    Question marks in subdivision names ( "Al Bay?a'")

    https://raw.githubusercontent.com/pariz/gountries/master/data/json/subdivisions/ye.json

    See: "Name": "Al Bay?a'",

    Do you suppose there's a way to add a subdivision.Names.Common - non-special char name for every subdivision like you have for country?

    opened by skillsourcegit 0
  • Countries missing

    Countries missing

    Found three countries missing:

    • AC (Ascension Island) https://www.iso.org/obp/ui/#iso:code:3166:AC
    • TA (Tristan da Cunha) https://www.iso.org/obp/ui/#iso:code:3166:TA
    • XK (Kosovo) https://countrycode.org/kosovo

    I'm not sure about last one, looks like there is some political context. But iso.org has AC and TA codes.

    opened by AlexanderMatveev 0
  • China is using old numeric codes for subdivisions

    China is using old numeric codes for subdivisions

    The codes for subdivisions in China are all numeric. This was changed in 2017-11-23 (see this).

    So the current code for Sichuan is 51, but should be SC

    opened by gcfresh 0
Releases(v0.1.6)
  • v0.1.6(Aug 12, 2022)

    What's Changed

    • Add support to query countries based on calling code by @rohithv-tw in https://github.com/pariz/gountries/pull/44
    • Add FindCountriesByCurrency by @perriea in https://github.com/pariz/gountries/pull/48

    New Contributors

    • @rohithv-tw made their first contribution in https://github.com/pariz/gountries/pull/44
    • @perriea made their first contribution in https://github.com/pariz/gountries/pull/48

    Full Changelog: https://github.com/pariz/gountries/compare/0.1.4...v0.1.6

    Source code(tar.gz)
    Source code(zip)
  • v0.1.5(Nov 29, 2021)

    Creating this release for compatibility to Go Modules (vMAJOR.MINOR.PATCH scheme).

    You can now import gountries in your go.mod as:

    require github.com/pariz/gountries v0.1.5
    
    Source code(tar.gz)
    Source code(zip)
  • 0.1.4(Nov 29, 2021)

    What's Changed

    • BQ & SH country support by @Youhar in https://github.com/pariz/gountries/pull/22
    • Add FindSubdivision(ByName|ByCode) by @tylerstillwater in https://github.com/pariz/gountries/pull/21
    • Add FindCountryByNativeName to take advantage of the available info by @pnfb in https://github.com/pariz/gountries/pull/26
    • Fix init queryInstance concurrent race by @bastengao in https://github.com/pariz/gountries/pull/32
    • runnable examples by @guillermo-menjivar in https://github.com/pariz/gountries/pull/31
    • Add FindSubdivisionCountryByName query by @machadovilaca in https://github.com/pariz/gountries/pull/37
    • Integrate github actions by @bastengao in https://github.com/pariz/gountries/pull/33
    • Add go.mod by @pbabbicola in https://github.com/pariz/gountries/pull/41
    • Use correct path for go.mod by @pbabbicola in https://github.com/pariz/gountries/pull/43

    New Contributors

    • @Youhar made their first contribution in https://github.com/pariz/gountries/pull/22
    • @tylerstillwater made their first contribution in https://github.com/pariz/gountries/pull/21
    • @pnfb made their first contribution in https://github.com/pariz/gountries/pull/26
    • @bastengao made their first contribution in https://github.com/pariz/gountries/pull/32
    • @guillermo-menjivar made their first contribution in https://github.com/pariz/gountries/pull/31
    • @machadovilaca made their first contribution in https://github.com/pariz/gountries/pull/37
    • @pbabbicola made their first contribution in https://github.com/pariz/gountries/pull/41

    Full Changelog: https://github.com/pariz/gountries/compare/0.1.3...0.1.4

    Updating name to prefix v so it works with go mod

    Source code(tar.gz)
    Source code(zip)
  • 0.1.1(Jul 30, 2017)

Owner
Pär Karlsson
I write computer code of the internets.
Pär Karlsson
Quickly collect data from thousands of exposed Elasticsearch or Kibana instances and generate a report to be reviewed.

elasticpwn Quickly collects data from exposed Elasticsearch or Kibana instances and generates a report to be reviewed. It mainly aims for sensitive da

Joel M 20 Aug 6, 2022
go.pipeline is a utility library that imitates unix pipeline. It simplifies chaining unix commands (and other stuff) in Go.

go.pipeline go.pipeline is a utility library that imitates unix pipeline. It simplifies chaining unix commands (and other stuff) in Go. Installation g

Song Gao 14 May 8, 2022
AutoK3s GEO collects metrics about locates remote IP-address and exposes metrics to InfluxDB.

AutoK3s GEO AutoK3s GEO collects metrics about locates remote IP-address and exposes metrics to InfluxDB. Thanks to https://freegeoip.live/ which prov

Jason 0 Jun 16, 2022
Input Geojson and utilize Dijkstra's formula to provide the best route between two sets of coordinates

Golang GeoJson Dijkstra Golang GeoJson Dijkstra utilizes GeoJson Feature Collections to find the best the shortest route between two points. Installat

Nate 9 May 26, 2022
The primary place where Optimism works on stuff related to Optimistic Ethereum

The Optimism Monorepo TL;DR This is the primary place where Optimism works on stuff related to Optimistic Ethereum. Documentation Extensive documentat

Onther Inc. Technology 0 Aug 8, 2022
Random fake data and struct generator for Go.

Faker Random fake data and struct generator for Go. More than 100 generator functions Struct generator Unique data generator Builtin types support Eas

Enrico 63 Jun 29, 2022
Workaround for running ubuntu:21.10, fedora:35, and other glibc >= 2.34 distros on Docker <= 20.10.9

clone3-workaround: Workaround for running ubuntu:21.10, fedora:35, and other glibc >= 2.34 distros on Docker <= 20.10.9 Old container engines such as

Akihiro Suda 7 Jun 17, 2022
Marquee for bar and other things.

Marquee for bar and other things.

Gabriel 1 Oct 5, 2021
Databases and dashboards loved each other so much that databoard was born.

databoard Work in progress tool to create API endpoints that executes queries on connected database. ⚠ The project is on early-development stage. Plan

Misir Jafarov 1 Nov 23, 2021
This example implements a basic example of how to create your own modules, and how to call them from other modules

This example implements a basic example of how to create your own modules, and how to call them from other modules. In addition, an example of how to do unit tests is developed.

null 1 Feb 1, 2022
Alerts on due products from Grocy through emails or other means.

grocy-alerts Grocy alerts was made in an attempt to give more visibility to expiring soon products in Grocy. Usage Fetch products from grocy api and c

Yann David 4 Dec 7, 2021
other glyph sets for high-dpi 1-bit monochrome

hd1b_other other glyph sets for high-dpi 1-bit monochrome Currently included glyph sets: Hangul (Korean): U+1100..U+11FF, U+3131..U+318E, U+AC00..U+D7

Sam Blenny 0 Jan 13, 2022
Provide Go Statistics Handler, Struct, Measure Method

Go Statistics Handler About The gosh is an abbreviation for Go Statistics Handler. This Repository is provided following functions. Go runtime statist

Osamu TONOMORI 29 Jul 24, 2022
RTS: request to struct. Generates Go structs from JSON server responses.

RTS: Request to Struct Generate Go structs definitions from JSON server responses. RTS defines type names using the specified lines in the route file

Paolo Galeone 232 Aug 10, 2022
Align Golang struct tags

Formattag The tool is used to align golang struct's tags. eg.: Before // TestStruct this is a test struct type TestStruct struct { ID stri

wentx 18 Aug 1, 2022
The kprobe package allows construction of dynamic struct based on kprobe event format descriptions.

The kprobe package allows construction of dynamic struct based on kprobe event format descriptions.

Dan Kortschak 4 Oct 27, 2021
An ease to use finit state machine golang implementation.Turn any struct to a fsm with graphviz visualization supported.

go-fsm An ease to use finit state machine golang implementation.Turn any struct to a fsm with graphviz visualization supported. usage import github.co

FingerLiu 5 Dec 26, 2021
Exercise for solve problem data processing, performance and something wrong in passing data

Citcall Exercise Exercise for solve problem data processing, performance and something wrong in passing data Pengolahan data data processing - Readme

Muhammad Fazri 0 Nov 25, 2021
Package buildinfo provides basic building blocks and instructions to easily add build and release information to your app.

Package buildinfo provides basic building blocks and instructions to easily add build and release information to your app. This is done by replacing variables in main during build with ldflags.

null 1 Nov 14, 2021