gophonenumbers

package module
v0.6.2 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2026 License: MIT Imports: 18 Imported by: 3

README

GoPhoneNumbers

Go CI Go Lint Go SAST Go Report Card Docs Visualization License

A Go library for phone number parsing, formatting, validation, and geolocation. Includes clients for Numverify and Twilio Lookup APIs.

Features

  • Phone Number Parsing: Parse E.164, national, and international formats
  • NANP Components: Extract area code, exchange code, and line number from North American numbers
  • Multiple Formats: Get E.164, national, international, and RFC3966 formats
  • Geolocation: US area code to geographic coordinates mapping (embedded data, no external files)
  • Distance Calculation: Great circle distance between area codes
  • Fictitious Numbers: Generate valid US fictitious phone numbers (555-01XX range)
  • API Clients: Numverify and Twilio Lookup API integrations
  • CLI Tools: Command-line apps for number validation and lookup

Installation

go get github.com/grokify/gophonenumbers

Quick Start

Parse and Format Phone Numbers
package main

import (
    "fmt"
    "github.com/grokify/gophonenumbers"
)

func main() {
    // Parse an E.164 number into multiple formats
    formats, err := gophonenumbers.FormatsParse("+16505551234", "US")
    if err != nil {
        panic(err)
    }

    fmt.Println("E.164:", formats.E164)           // +16505551234
    fmt.Println("National:", formats.National)    // (650) 555-1234
    fmt.Println("International:", formats.International) // +1 650-555-1234
    fmt.Println("RFC3966:", formats.RFC3966)      // tel:+1-650-555-1234
}
Extract NANP Components
package main

import (
    "fmt"
    "github.com/grokify/gophonenumbers"
)

func main() {
    num := gophonenumbers.Number{E164Number: "+16505551234"}
    comp, err := num.NANPComponents()
    if err != nil {
        panic(err)
    }

    fmt.Println("Country Code:", comp.CountryCode)     // 1
    fmt.Println("Area Code:", comp.NANPAreaCode)       // 650
    fmt.Println("Exchange Code:", comp.NANPExchangeCode) // 555
    fmt.Println("Line Number:", comp.NANPLineNumber)   // 1234
}
US Area Code Geolocation

The library includes embedded US area code geolocation data - no external files required.

package main

import (
    "fmt"
    "github.com/grokify/gophonenumbers"
)

func main() {
    // Load embedded area code data
    a2g := gophonenumbers.NewAreaCodeToGeo()
    if err := a2g.ReadData(); err != nil {
        panic(err)
    }

    // Get area code info
    aci := a2g.AreaCodeInfos[650] // San Francisco Bay Area
    fmt.Printf("Area Code 650: Lat %.4f, Lon %.4f\n",
        aci.Point.Lat(), aci.Point.Lng())

    // Calculate distance between area codes
    dist, _ := a2g.GcdAreaCodes(650, 212) // SF to NYC
    fmt.Printf("Distance 650 to 212: %.0f km\n", dist)
}
Generate Fictitious Phone Numbers

Generate valid US fictitious numbers in the 555-01XX range for testing:

package main

import (
    "fmt"
    "github.com/grokify/gophonenumbers"
)

func main() {
    a2g := gophonenumbers.NewAreaCodeToGeo()
    if err := a2g.ReadData(); err != nil {
        panic(err)
    }

    fng := gophonenumbers.NewFakeNumberGenerator(a2g.AreaCodes())

    // Generate a random fictitious number
    num, _ := fng.RandomLocalNumberUS()
    fmt.Printf("Fictitious number: +%d\n", num)

    // Generate unique numbers
    set := map[uint64]int8{}
    for i := 0; i < 5; i++ {
        num, set, _ = fng.RandomLocalNumberUSUnique(set)
        fmt.Printf("Unique number %d: +%d\n", i+1, num)
    }
}

API Clients

Numverify

Validate phone numbers using the Numverify API:

package main

import (
    "fmt"
    nv "github.com/grokify/gophonenumbers/numverify"
)

func main() {
    client := nv.Client{AccessKey: "your-access-key"}

    resp, _, _, err := client.Validate(nv.Params{Number: "+16505551234"})
    if err != nil {
        panic(err)
    }

    if resp.Success != nil {
        fmt.Println("Valid:", resp.Success.Valid)
        fmt.Println("Carrier:", resp.Success.Carrier)
        fmt.Println("Line Type:", resp.Success.LineType)
    }
}
Twilio Lookup

Look up phone numbers using the Twilio Lookup API:

package main

import (
    "fmt"
    "github.com/grokify/gophonenumbers/twilio"
)

func main() {
    client := twilio.NewClient("account-sid", "auth-token")

    info, err := client.Validate("+16505551234", &twilio.Params{Type: "carrier"})
    if err != nil {
        panic(err)
    }

    fmt.Println("Phone Number:", info.PhoneNumber)
    fmt.Println("Carrier:", info.Carrier.Name)
}

CLI Tools

Numverify CLI
# Install
go install github.com/grokify/gophonenumbers/cmd/numverify@latest

# Validate a number
numverify -t=<access-key> -n=+16505551234

# Using .env file
numverify -e=/path/to/.env -n=+16505551234

# List supported countries
numverify -t=<access-key> -c
Area Code Distance
# Install
go install github.com/grokify/gophonenumbers/cmd/areacode_distance@latest

# Calculate distance between area codes
areacode_distance 650 212

Data Reference

Embedded Data

The library embeds US area code geolocation data from the Area Code Geolocation Database. No external files or GOPATH configuration required.

Number Components
Component Description Example
Country Code ITU-T E.164 country code 1 (US/Canada)
Area Code (NPA) Numbering Plan Area code 650
Exchange Code (NXX) Central office code 555
Line Number Subscriber number 1234
Fictitious Numbers

The library generates numbers in the reserved 555-01XX range per NANPA guidelines. These numbers are safe for testing and will never conflict with real numbers.

Contributing

Contributions are welcome. Please open an issue or submit a pull request.

License

MIT License - see LICENSE for details.

Documentation

Index

Constants

View Source
const (
	CarrierATT     = "att"
	CarrierSprint  = "sprint"
	CarrierTMobile = "tmobile"
	CarrierVerizon = "verizon"

	LineTypeLocal    = "local"
	LineTypeMobile   = "mobile"
	LineTypeTollFree = "tollfree"

	SourceEkata     = "ekata"
	SourceNumverify = "numverify"
	SourcePlivo     = "plivo"
	SourceTwilio    = "twilio"
)

Variables

This section is empty.

Functions

func AreaCodeGeoCSV added in v0.6.0

func AreaCodeGeoCSV() []byte

AreaCodeGeoCSV returns the embedded US area code geolocation CSV data. This data is from https://github.com/ravisorg/Area-Code-Geolocation-Database

func E164Format added in v0.3.0

func E164Format(numberToParse, defaultRegion string, numberFormat phonenumbers.PhoneNumberFormat) (string, error)

func LetterToNumberMap added in v0.3.0

func LetterToNumberMap() map[string]int

func LocalNumberUS added in v0.3.0

func LocalNumberUS(ac uint16, ln uint16) uint64

LocalNumberUS returns a US E.164 number given an areacode and line number

func MustE164Format added in v0.3.0

func MustE164Format(numberToParse, defaultRegion string, numberFormat phonenumbers.PhoneNumberFormat) string

func NewPointString added in v0.3.0

func NewPointString(lat string, lon string) (*geo.Point, error)

NewPointString returns a *geo.Point based on string lat and lon values.

func StringToNumbers added in v0.3.0

func StringToNumbers(s string) string

Types

type AreaCodeIncrementor added in v0.3.0

type AreaCodeIncrementor struct {
	Counter map[uint16]uint16
	Base    uint16
}

func NewAreaCodeIncrementor added in v0.3.0

func NewAreaCodeIncrementor(base uint16) AreaCodeIncrementor

func (*AreaCodeIncrementor) GetNext added in v0.3.0

func (aci *AreaCodeIncrementor) GetNext(ac uint16) uint64

type AreaCodeInfo added in v0.3.0

type AreaCodeInfo struct {
	AreaCode uint16
	Point    *geo.Point
}

func NewAreaCodeInfoStrings added in v0.3.0

func NewAreaCodeInfoStrings(ac, lat, lon string) (AreaCodeInfo, error)

NewAreaCodeInfoStrings returns an AreaCodeInfo based on string area code, lat and lon values.

type AreaCodeToGeo added in v0.3.0

type AreaCodeToGeo struct {
	AreaCodeInfos  map[uint16]AreaCodeInfo
	DistanceMatrix map[uint16]map[uint16]float64
}

func NewAreaCodeToGeo added in v0.3.0

func NewAreaCodeToGeo() AreaCodeToGeo

func (*AreaCodeToGeo) AreaCodeSlice added in v0.3.0

func (a2g *AreaCodeToGeo) AreaCodeSlice() []AreaCodeInfo

func (*AreaCodeToGeo) AreaCodes added in v0.3.0

func (a2g *AreaCodeToGeo) AreaCodes() []uint16

func (*AreaCodeToGeo) AreaCodesSorted added in v0.3.0

func (a2g *AreaCodeToGeo) AreaCodesSorted() []uint16

func (*AreaCodeToGeo) GcdAreaCodes added in v0.3.0

func (a2g *AreaCodeToGeo) GcdAreaCodes(ac1Int uint16, ac2Int uint16) (float64, error)

func (*AreaCodeToGeo) GetDistanceMatrix added in v0.3.0

func (a2g *AreaCodeToGeo) GetDistanceMatrix() map[uint16]map[uint16]float64

func (*AreaCodeToGeo) Inflate added in v0.3.0

func (a2g *AreaCodeToGeo) Inflate()

func (*AreaCodeToGeo) ReadCSVBytes added in v0.6.0

func (a2g *AreaCodeToGeo) ReadCSVBytes(data []byte) error

ReadCSVBytes reads area code data from a CSV byte slice.

func (*AreaCodeToGeo) ReadData added in v0.3.0

func (a2g *AreaCodeToGeo) ReadData() error

ReadData loads the embedded US area code geolocation data.

type CarrierNumberInfo added in v0.2.0

type CarrierNumberInfo struct {
	E164Number        string `json:"e164Number"`
	MobileCountryCode string `json:"mobileCountryCode,omitempty"`
	MobileNetworkCode string `json:"mobileNetworkCode,omitempty"`
	Name              string `json:"name,omitempty"`
	LineType          string `json:"lineType,omitempty"`
	ErrorCode         string `json:"errorCode,omitempty"`
}

type Components

type Components struct {
	E164Number       string
	E164NumberUint   uint
	RegionCode       string
	CountryCode      uint
	NANPAreaCode     uint // NPA - Numbering plan area code
	NANPExchangeCode uint // NXX - Central office (exchange) code
	NANPLineNumber   uint // xxxx - Line number or subscriber number
}

type FakeNumberGenerator added in v0.3.0

type FakeNumberGenerator struct {
	AreaCodes []uint16
}

func NewFakeNumberGenerator added in v0.3.0

func NewFakeNumberGenerator(areacodes []uint16) FakeNumberGenerator

func (*FakeNumberGenerator) LocalNumberUS added in v0.3.0

func (fng *FakeNumberGenerator) LocalNumberUS(ac uint16, ln uint16) uint64

LocalNumberUS returns a US E.164 number given an areacode and line number

func (*FakeNumberGenerator) RandomAreaCode added in v0.3.0

func (fng *FakeNumberGenerator) RandomAreaCode() uint16

RandomAreaCode generates a random area code.

func (*FakeNumberGenerator) RandomLineNumber added in v0.3.0

func (fng *FakeNumberGenerator) RandomLineNumber() uint16

RandomLineNumber generates a random line number

func (*FakeNumberGenerator) RandomLineNumberMinMax added in v0.3.0

func (fng *FakeNumberGenerator) RandomLineNumberMinMax(min, max uint16) uint16

RandomLineNumber generates a random line number

func (*FakeNumberGenerator) RandomLocalNumberUS added in v0.3.0

func (fng *FakeNumberGenerator) RandomLocalNumberUS() (uint64, error)

RandomLocalNumberUS returns a US E.164 number AreaCode + Prefix + Line Number

func (*FakeNumberGenerator) RandomLocalNumberUSAreaCodes added in v0.3.0

func (fng *FakeNumberGenerator) RandomLocalNumberUSAreaCodes(acs []uint16) uint64

RandomLocalNumberUS returns a US E.164 number AreaCode + Prefix + Line Number

func (*FakeNumberGenerator) RandomLocalNumberUSUnique added in v0.3.0

func (fng *FakeNumberGenerator) RandomLocalNumberUSUnique(set map[uint64]int8) (uint64, map[uint64]int8, error)

RandomLocalNumberUSUnique returns a US E.164 number AreaCode + Prefix + Line Number

func (*FakeNumberGenerator) RandomLocalNumberUSUniqueAreaCodeSet added in v0.3.0

func (fng *FakeNumberGenerator) RandomLocalNumberUSUniqueAreaCodeSet(set map[uint64]int8, acs []uint16) (uint64, map[uint64]int8, error)

RandomLocalNumberUSUnique returns a US E.164 number AreaCode + Prefix + Line Number

type Formats added in v0.5.0

type Formats struct {
	E164          string
	International string
	National      string
	RFC3966       string
}

func FormatsFromPhoneNumber added in v0.5.0

func FormatsFromPhoneNumber(pn *phonenumbers.PhoneNumber) Formats

func FormatsParse added in v0.5.0

func FormatsParse(number, region string) (Formats, error)

type Lookup added in v0.2.0

type Lookup struct {
	CarrierNumberInfo CarrierNumberInfo      `json:"carrierNumberInfo"`
	LookupSource      string                 `json:"lookupSource"`
	LookupTime        time.Time              `json:"lookupTime"`
	LookupResponse    map[string]interface{} `json:"lookupResponse"`
}

type LookupSet added in v0.2.0

type LookupSet struct {
	LookupMap map[string]Lookup `json:"lookupMap"`
}

func NewLookupSet added in v0.2.0

func NewLookupSet() LookupSet

func (LookupSet) Add added in v0.2.0

func (set LookupSet) Add(lookup Lookup)

func (LookupSet) Latest added in v0.2.0

func (set LookupSet) Latest(source string) (Lookup, error)

func (LookupSet) Validate added in v0.2.0

func (set LookupSet) Validate()

type MapStringString added in v0.2.0

type MapStringString map[string]string

type Number added in v0.2.0

type Number struct {
	E164Number        string            `json:"e164Number"`
	CountryCode       string            `json:"countryCode"`
	CarrierNumberInfo CarrierNumberInfo `json:"carrier"`
	Lookups           LookupSet         `json:"lookups"`
}

func NewNumber added in v0.2.0

func NewNumber() Number

func (*Number) NANPComponents added in v0.2.0

func (num *Number) NANPComponents() (Components, error)

func (*Number) RemoveLookups added in v0.3.0

func (num *Number) RemoveLookups()

func (*Number) SetLatest added in v0.2.0

func (num *Number) SetLatest(source string) error

type NumberSet added in v0.2.0

type NumberSet struct {
	Numbers map[string]Number `json:"numbers"`
}

func NewNumberSet added in v0.2.0

func NewNumberSet() NumberSet

func (*NumberSet) Add added in v0.2.0

func (set *NumberSet) Add(num Number) error

func (*NumberSet) HistogramCarrierName added in v0.3.0

func (set *NumberSet) HistogramCarrierName() map[string]int

func (*NumberSet) MapNumberCarrierName added in v0.2.0

func (set *NumberSet) MapNumberCarrierName() map[string]string

func (*NumberSet) MapNumberLineType added in v0.2.0

func (set *NumberSet) MapNumberLineType() map[string]string

func (*NumberSet) RemoveLookups added in v0.3.0

func (set *NumberSet) RemoveLookups()

func (*NumberSet) Validate added in v0.3.0

func (set *NumberSet) Validate() error

func (*NumberSet) WriteFileJSON added in v0.2.0

func (set *NumberSet) WriteFileJSON(filename, prefix, indent string, perm fs.FileMode) error

Directories

Path Synopsis
cmd
numverify command
parsenumber command

Jump to

Keyboard shortcuts

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