-
Notifications
You must be signed in to change notification settings - Fork 16
/
address.go
444 lines (346 loc) · 12.8 KB
/
address.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//go:generate go run generator/generate.go
// Package address is a library that validates and formats addresses using data generated from Google's Address
// Data Service.
package address
import (
"fmt"
"sort"
"strings"
"golang.org/x/text/collate"
textLanguage "golang.org/x/text/language"
"golang.org/x/text/language/display"
)
type formatData struct {
Country string
CountryEnglish string
Name string
Organization string
StreetAddress []string
DependentLocality string
Locality string
AdministrativeArea string
AdministrativeAreaPostalKey string
PostCode string
SortingCode string
}
// Address represents a valid address made up of its child components.
type Address struct {
Country string
Name string
Organization string
StreetAddress []string
DependentLocality string
Locality string
AdministrativeArea string
PostCode string
SortingCode string
}
// IsZero reports whether a represents a zero/uninitialized address
func (a Address) IsZero() bool {
return a.Country == "" && a.Name == "" && a.Organization == "" && len(a.StreetAddress) <= 0 && a.DependentLocality == "" && a.Locality == "" && a.AdministrativeArea == "" && a.PostCode == "" && a.SortingCode == ""
}
func (a Address) toFormatData(countryData country, language string) formatData {
f := formatData{
Name: a.Name,
Organization: a.Organization,
StreetAddress: []string{},
DependentLocality: a.DependentLocality,
Locality: a.Locality,
AdministrativeArea: a.AdministrativeArea,
PostCode: a.PostCode,
SortingCode: a.SortingCode,
}
for _, addressLine := range a.StreetAddress {
trimmed := strings.TrimSpace(addressLine)
if trimmed != "" {
f.StreetAddress = append(f.StreetAddress, trimmed)
}
}
normalizedLanguage := generated.normalizeLanguage(countryData.ID, language)
namer := display.Regions(textLanguage.MustParse(normalizedLanguage))
country := textLanguage.MustParseRegion(countryData.ID)
if namer != nil {
f.Country = namer.Name(country)
} else {
namer = display.Regions(textLanguage.English)
f.Country = namer.Name(country)
}
if a.AdministrativeArea != "" {
if adminAreaName := generated.getAdministrativeAreaName(a.Country, a.AdministrativeArea, language); adminAreaName != "" {
f.AdministrativeArea = adminAreaName
}
f.AdministrativeAreaPostalKey = generated.getAdministrativeAreaPostalKey(a.Country, a.AdministrativeArea)
}
if a.Locality != "" {
if localityName := generated.getLocalityName(a.Country, a.AdministrativeArea, a.Locality, language); localityName != "" {
f.Locality = localityName
}
}
if a.DependentLocality != "" {
if dependentLocalityName := generated.getDependentLocalityName(a.Country, a.AdministrativeArea, a.Locality, a.DependentLocality, language); dependentLocalityName != "" {
f.DependentLocality = dependentLocalityName
}
}
return f
}
// NewValid creates a new Address. If the address is invalid, an error is returned.
// In the case where an error is returned, the error is a hashicorp/go-multierror (https://github.com/hashicorp/go-multierror).
// You can use a type switch to get a list of validation errors for the address.
func NewValid(fields ...func(*Address)) (Address, error) {
address := New(fields...)
err := Validate(address)
if err != nil {
return address, fmt.Errorf("invalid address: %w", err)
}
return address, nil
}
// New creates a new unvalidated address. The validity of the address should be checked
// using the validator.
func New(fields ...func(*Address)) Address {
address := Address{}
for _, field := range fields {
field(&address)
}
return address
}
// WithCountry sets the country code of an address.
// The country code must be an ISO 3166-1 country code.
func WithCountry(countryCode string) func(*Address) {
return func(a *Address) {
a.Country = strings.ToUpper(countryCode)
}
}
// WithName sets the addressee's name of an address.
func WithName(name string) func(*Address) {
return func(a *Address) {
a.Name = name
}
}
// WithOrganization sets the addressee's organization of an address.
func WithOrganization(organization string) func(*Address) {
return func(a *Address) {
a.Organization = organization
}
}
// WithStreetAddress sets the street address of an address.
// The street address is a slice of strings, with each element representing an address line.
func WithStreetAddress(streetAddress []string) func(*Address) {
return func(a *Address) {
a.StreetAddress = streetAddress
}
}
// WithDependentLocality sets the dependent locality (commonly known as the suburb) of an address.
// If the country of the address has a list of dependent localities, then the key of the dependent locality should
// be used, otherwise, the validation will fail.
func WithDependentLocality(dependentLocality string) func(*Address) {
return func(a *Address) {
a.DependentLocality = dependentLocality
}
}
// WithLocality sets the locality (commonly known as the city) of an address.
// If the country of the address has a list of localities, then the key of the locality should be used, otherwise,
// the validation will fail.
func WithLocality(locality string) func(*Address) {
return func(a *Address) {
a.Locality = locality
}
}
// WithAdministrativeArea sets the administrative area (commonly known as the state) of an address.
// If the country of the address has a list of administrative area, then the key of the administrative area should
// used, otherwise, the validation will fail.
func WithAdministrativeArea(administrativeArea string) func(*Address) {
return func(a *Address) {
a.AdministrativeArea = administrativeArea
}
}
// WithPostCode sets the post code of an address.
func WithPostCode(postCode string) func(*Address) {
return func(a *Address) {
a.PostCode = postCode
}
}
// WithSortingCode sets the sorting code of an address.
func WithSortingCode(sortingCode string) func(*Address) {
return func(a *Address) {
a.SortingCode = sortingCode
}
}
// CountryData contains the address data for a country.
// The AdministrativeAreas field contains a list of nested subdivisions (administrative areas, localities and dependent
// localities) grouped by their translated languages. They are also sorted according to the sort order of the languages
// they are in.
type CountryData struct {
Format string
LatinizedFormat string
Required []Field
Allowed []Field
DefaultLanguage string
AdministrativeAreaNameType FieldName
LocalityNameType FieldName
DependentLocalityNameType FieldName
PostCodeNameType FieldName
PostCodeRegex PostCodeRegexData
AdministrativeAreas map[string][]AdministrativeAreaData
}
// PostCodeRegexData contains regular expressions for validating post codes for a given country.
// If the country has subdivisions (administrative areas, localities and dependent localities), the SubdivisionRegex
// field may contain further regular expressions to Validate the post code.
type PostCodeRegexData struct {
Regex string
SubdivisionRegex map[string]PostCodeRegexData
}
// AdministrativeAreaData contains the name and ID of and administrative area. The ID must be passed to
// WithAdministrativeArea() when creating an address. The name is useful for displaying to the end user.
type AdministrativeAreaData struct {
ID string
Name string
Localities []LocalityData
}
// LocalityData contains the name and ID of and administrative area. The ID must be passed to
// WithLocalityData() when creating an address. The name is useful for displaying to the end user.
type LocalityData struct {
ID string
Name string
DependentLocalities []DependentLocalityData
}
// DependentLocalityData contains the name and ID of and administrative area. The ID must be passed to
// WithDependentLocalityData() when creating an address. The name is useful for displaying to the end user.
type DependentLocalityData struct {
ID string
Name string
}
// CountryList contains a list of countries that can be used to create addresses.
type CountryList []CountryListItem
// Len returns the number of countries in the list. This is used for sorting the countries and would not generally be used
// in client code.
func (c CountryList) Len() int {
return len(c)
}
// Swap swaps 2 countries in the list. This is used for sorting the countries and would not generally be used
// in client code.
func (c CountryList) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
}
// Bytes returns a country name in bytes. This is used for sorting the countries and would not generally be used
// in client code.
func (c CountryList) Bytes(i int) []byte {
return []byte(c[i].Name)
}
// CountryListItem represents a single country, containing the ISO 3166-1 code and the name of the country.
type CountryListItem struct {
Code string
Name string
}
// ListCountries returns a list of countries that can be used to create addresses.
// Language must be a valid ISO 639-1 language code such as: en, jp, zh, etc.
// If the language does not have any translations or is invalid, then English is used as the fallback language.
// The returned list of countries is sorted according to the chosing language.
func ListCountries(language string) []CountryListItem {
l, err := textLanguage.Parse(language)
if err != nil {
l = textLanguage.English
}
c := collate.New(l)
namer := display.Regions(l)
if namer == nil {
namer = display.Regions(textLanguage.English)
}
var countries CountryList
for countryCode := range generated {
if countryCode == "ZZ" {
continue
}
country := textLanguage.MustParseRegion(countryCode)
countries = append(countries, CountryListItem{
Code: countryCode,
Name: namer.Name(country),
})
}
c.Sort(countries)
return countries
}
// GetCountry returns address information for a given country.
func GetCountry(countryCode string) CountryData {
country := generated.getCountry(countryCode)
return internalCountryDataToCountryData(country)
}
func internalCountryDataToCountryData(country country) CountryData {
data := CountryData{
Format: country.Format,
LatinizedFormat: country.LatinizedFormat,
DefaultLanguage: country.DefaultLanguage,
AdministrativeAreaNameType: country.AdministrativeAreaNameType,
LocalityNameType: country.LocalityNameType,
DependentLocalityNameType: country.DependentLocalityNameType,
PostCodeNameType: country.PostCodeNameType,
PostCodeRegex: internalPostCodeRegexToPostCodeRegexData(country.PostCodeRegex),
}
var required []Field
for field := range country.RequiredFields {
required = append(required, field)
}
sort.Slice(required, func(i, j int) bool {
return required[i].String() < required[j].String()
})
data.Required = required
var allowed []Field
for field := range country.AllowedFields {
allowed = append(allowed, field)
}
sort.Slice(allowed, func(i, j int) bool {
return allowed[i].String() < allowed[j].String()
})
data.Allowed = allowed
administrativeAreas := map[string][]AdministrativeAreaData{}
for lang, adminAreas := range country.AdministrativeAreas {
administrativeAreas[lang] = internalAdministrativeAreasToAdministrativeAreaData(adminAreas)
}
if len(administrativeAreas) > 0 {
data.AdministrativeAreas = administrativeAreas
}
return data
}
func internalPostCodeRegexToPostCodeRegexData(regex postCodeRegex) PostCodeRegexData {
result := PostCodeRegexData{
Regex: regex.regex,
}
for subID, regex := range regex.subdivisionRegex {
if result.SubdivisionRegex == nil {
result.SubdivisionRegex = map[string]PostCodeRegexData{}
}
result.SubdivisionRegex[subID] = internalPostCodeRegexToPostCodeRegexData(regex)
}
return result
}
func internalAdministrativeAreasToAdministrativeAreaData(areas []administrativeArea) []AdministrativeAreaData {
var result []AdministrativeAreaData
for _, adminArea := range areas {
var localities []LocalityData
for _, locality := range adminArea.Localities {
var dependentLocalities []DependentLocalityData
for _, dependentLocality := range locality.DependentLocalities {
dependentLocalities = append(dependentLocalities, DependentLocalityData{
ID: dependentLocality.ID,
Name: dependentLocality.Name,
})
}
localityData := LocalityData{
ID: locality.ID,
Name: locality.Name,
}
if len(dependentLocalities) > 0 {
localityData.DependentLocalities = dependentLocalities
}
localities = append(localities, localityData)
}
adminAreaData := AdministrativeAreaData{
ID: adminArea.ID,
Name: adminArea.Name,
}
if len(localities) > 0 {
adminAreaData.Localities = localities
}
result = append(result, adminAreaData)
}
return result
}