Address handling for Go.

address Build Status Coverage Status Go Report Card PkgGoDev

Handles address representation, validation and formatting.

Inspired by Google's libaddressinput.

Backstory: https://bojanz.github.io/address-handling-go/

Features

  1. Address struct.
  2. Address formats for ~200 countries.
  3. Regions for ~40 countries, with local names where relevant (e.g: Okinawa / 沖縄県).
  4. Country list, powered by CLDR v38.
  5. HTML formatter.
  6. HTTP handler for serving address formats and regions as JSON: only ~14kb gzipped!

Address struct

Represents an address as commonly handled by web applications and APIs.

type Address struct {
	Line1 string
	Line2 string
	Line3 string
	// Sublocality is the neighborhood/suburb/district.
	Sublocality string
	// Locality is the city/village/post town.
	Locality string
	// Region is the state/province/prefecture.
	// An ISO code is used when available.
	Region string
	// PostalCode is the postal/zip/pin code.
	PostalCode string
	// CountryCode is the two-letter code as defined by CLDR.
	CountryCode string
}

Recipient fields such as FirstName/LastName are not included since they are usually present on the parent (Contact/Customer/User) struct. This allows the package to avoid being opinionated about name handling.

There are three line fields, matching the HTML5 autocomplete spec and many shipping APIs. This leaves enough space for specifying an organization and department, house or hotel name, and other similar "care of" use cases. When mapping to an API that only has two address lines, Line3 can be appended to Line2, separated by a comma.

Address formats

The following information is available:

  • Which fields are used, and in which order.
  • Which fields are required.
  • Labels for the sublocality, locality, region and postal code fields.
  • Regular expression pattern for validating postal codes.
  • Regions and how to display them in an address.

Certain countries (e.g. China, Japan, Russia, Ukraine) have region names defined in both Latin and local scripts. The script is selected based on locale. For example, the "ru" locale will use Russian regions in Cyrilic, while "ru-Latn" and other locales will use the Latin version.

Helpers are provided for validating required fields, regions, postal codes.

Format data was generated from Google's Address Data but isn't automatically regenerated, to allow the community to submit their own corrections directly to the package.

Countries

The country list is auto-generated from CLDR. Updating to the latest CLDR release is always one go generate away.

Most software uses the CLDR country list instead of the ISO one because the CLDR country names match their colloquial usage more closely (e.g. "Russia" instead of "Russian Federation").

To reduce the size of the included data, this package only includes country names in English. Translated country names can be fetched on the frontend via Intl.DisplayNames. Alternatively, one can plug in x/text/language/display by setting a custom CountryMapper on the formatter.

Formatter

Displays an address as HTML, using the country's address format.

The wrapper element ("p") and class ("address") can be configured. The country name can be omitted, for the use case where all addresses belong to the same country.

addr := address.Address{
    Line1:       "1098 Alta Ave",
    Locality:    "Mountain View",
    Region:      "CA",
    PostalCode:  "94043",
    CountryCode: "US",
}
locale := address.NewLocale("en")
formatter := address.NewFormatter(locale)
output := formatter.Format(addr)
// Output:
// <p class="address" translate="no">
// <span class="line1">1098 Alta Ave</span><br>
// <span class="locality">Mountain View</span>, <span class="region">CA</span> <span class="postal-code">94043</span><br>
// <span class="country" data-value="US">United States</span>
// </p>

addr = address.Address{
    Line1:       "幸福中路",
    Sublocality: "新城区",
    Locality:    "西安市",
    Region:      "SN",
    PostalCode:  "710043",
    CountryCode: "CN",
}
locale := address.NewLocale("zh")
formatter := address.NewFormatter(locale)
formatter.NoCountry = true
formatter.WrapperElement = "div"
formatter.WrapperClass = "postal-address"
output := formatter.Format(addr)
// Output:
// <div class="postal-address" translate="no">
// <span class="postal-code">710043</span><br>
// <span class="region">陕西省</span><span class="locality">西安市</span><span class="sublocality">新城区</span><br>
// <span class="line1">幸福中路</span>
// </div>
Similar Resources

Handling Google Authenitcator codes.

Handling Google Authenitcator codes.

gotp Handling Google Authenticator codes in your terminal Getting started Grab the binary The quickest way to get set up is to download the latest bin

Aug 19, 2022

YTask is an asynchronous task queue for handling distributed jobs in golang

YTask is an asynchronous task queue for handling distributed jobs in golang

YTask is an asynchronous task queue for handling distributed jobs in golang

Dec 24, 2022

RPC over libp2p pubsub with error handling

go-libp2p-pubsub-rpc RPC over libp2p pubsub with error handling Table of Contents Background Install Usage Contributing Changelog License Background g

Dec 14, 2022

Package shapes provides an algebra for handling shapes

About Package shapes provides the algebra and machinery for dealing with the metainformation of shapes of a tensor. Why a shape package? The shape pac

Jan 14, 2022

Simple Kubernetes operator for handling echo CRDs 🤖

echoperator 🤖 Simple Kubernetes operator for handling echo CRDs. Kubernetes operator pattern implementation using the client-go library. Altough ther

Dec 19, 2022

mini tools handling migrasion database from cli

mini tools handling migrasion database from cli

Dec 13, 2021

Declarative error handling for Go.

ErrorFlow Declarative error handling for Go. Motivation Reading list: Don't defer Close() on writable files Error Handling — Problem Overview Proposal

Mar 3, 2022

StaticBackend is a simple backend server API handling user mgmt, database, storage and real-time component

StaticBackend is a simple backend server API handling user mgmt, database, storage and real-time component

StaticBackend is a simple backend that handles user management, database, file storage, forms, and real-time experiences via channel/topic-based communication for web and mobile applications.

Jan 7, 2023

Generic error handling with panic, recover, and defer.

Generic error handling with panic, recover, and defer.

Aug 25, 2022

handling 1M websockets connections in Go

Going Infinite, handling 1M websockets connections in Go This repository holds the complete implementation of the examples seen in Gophercon Israel ta

Jan 1, 2023

GoTrue is a small open-source API written in Golang, that can act as a self-standing API service for handling user registration and authentication for Jamstack projects.

GoTrue is a small open-source API written in Golang, that can act as a self-standing API service for handling user registration and authentication for Jamstack projects.

GoTrue is a small open-source API written in Golang, that can act as a self-standing API service for handling user registration and authentication for Jamstack projects.

Dec 13, 2021

Go server for handling WebSub, supporting custom implementations of content providers.

Go WebSub Server A Go implementation of a WebSub server. See examples/main.go for a basic example which uses boltdb and a simple publisher. Importing:

Dec 13, 2022

brief: a piece of error handling codelet

brief a piece of error handling codelet. this code only demonstrates how to hide sql.ErrNoRows to the caller. the Get() method defined in the pkg/proj

Oct 30, 2021

A Git RPC service for handling all the git calls made by GitLab

A Git RPC service for handling all the git calls made by GitLab

Quick Links: Roadmap | Want to Contribute? | GitLab Gitaly Issues | GitLab Gitaly Merge Requests | Gitaly is a Git RPC service for handling all the gi

Nov 13, 2021

Just another error handling primitives for golang

errors Just another error handling primitives for golang Install go install github.com/WAY29/errors@latest Usage New error and print error context Th

Feb 19, 2022

A very simple Golang server handling basic GET and POST requests

GOLANG SERVER INTRO As a true Blockchain enthusiast, I had to learn Solidity and Golang to participate to several projects. This repository consists o

Nov 17, 2021

An API for handling file meta data

dp-files-api An API for handling file meta data Getting started Run make debug Dependencies No further dependencies other than those defined in go.mod

Jan 4, 2022

GOWS is GoLang web-socket module Provides you with ease of handling web socket connections with a few lines

GOWS GOWS is GoLang web-socket module Provides you with ease of handling web socket connections with a few lines, it supports multi-connection on one

Apr 4, 2022

🥷 CError (Custom Error Handling)

🥷 CError (Custom Error Handling) Installation Via go packages: go get github.com/rozturac/cerror Usage Here is a sample CError uses: import ( "gi

Sep 21, 2022
Comments
  • Evaluate if certain countries should only have a single address line

    Evaluate if certain countries should only have a single address line

    Right now every address format contains address lines 1 and 2. However, over the years I've seen reports of various countries preferring to have a single address line. Reported at https://github.com/google/libaddressinput/issues/61 back in 2014. The list of countries mentioned back then is:

    Australia, Estonia, Latvia, Lithuania, New Zealand, Russia, Finland
    

    Since bojanz/address maintains its own address format dataset (instead of regenerating it from Google's data like commerceguys/addressing does), we could easily modify relevant address formats, removing the %2 token. But this is going to need community confirmation, and fresh research.

  • The HTTP handler outputs regions in the wrong order

    The HTTP handler outputs regions in the wrong order

    We use a map for regions, which means that it doesn't retain the order of the elements, the regions get reordered alphabetically by key during JSON encoding.

    We need to introduce an ordered map for regions. We can tailor it to our use case, for example there is no need to have Delete().

Simple error handling primitives

errors Package errors provides simple error handling primitives. go get github.com/pkg/errors The traditional error handling idiom in Go is roughly ak

Dec 26, 2022
A comprehensive error handling library for Go

Highlights The errorx library provides error implementation and error-related utilities. Library features include (but are not limited to): Stack trac

Jan 6, 2023
a tool for handling file uploads simple

baraka a tool for handling file uploads for http servers makes it easier to make operations with files from the http request. Contents Install Simple

Nov 30, 2022
Currency handling for Go.

currency Handles currency amounts, provides currency information and formatting. Powered by CLDR v38, in just ~30kb of data. Backstory: https://bojanz

Jan 3, 2023
A sync.WaitGroup with error handling and concurrency control

go-waitgroup How to use An package that allows you to use the constructs of a sync.WaitGroup to create a pool of goroutines and control the concurrenc

Dec 31, 2022
:speedboat: a limited consumer goroutine or unlimited goroutine pool for easier goroutine handling and cancellation

Package pool Package pool implements a limited consumer goroutine or unlimited goroutine pool for easier goroutine handling and cancellation. Features

Jan 1, 2023
A Go package for handling common HTTP JSON responses.

go-respond A Go package for handling common HTTP JSON responses. Installation go get github.com/nicklaw5/go-respond Usage The goal of go-respond is to

Sep 26, 2022
handling 1M websockets connections in Go

Going Infinite, handling 1M websockets connections in Go This repository holds the complete implementation of the examples seen in Gophercon Israel ta

Jan 8, 2023
reasonable handling of nullable values

null import "gopkg.in/guregu/null.v4" null is a library with reasonable options for dealing with nullable SQL and JSON values There are two packages:

Dec 28, 2022
😴 A tiny library for handling system interrupts

Wait a bit Tiny library for manage you application shutdown in graceful way by catching the OS signals. Documentation Installation go get -u github.co

Nov 25, 2022