Documentation
¶
Overview ¶
Package msisdn is a developer-friendly phone number toolkit for backend systems, fintech, CRM, telecom, and iGaming platforms: parsing, validation, normalization, formatting, type/operator detection, masking, and batch helpers, built around a single Phone value type.
Index ¶
- func Clean(number string) string
- func Dedupe(numbers []string, defaultRegion string) []string
- func Equal(number1, number2 string, defaultRegion ...string) bool
- func Example(iso string) (string, error)
- func Format(number, region string, style Style) (string, error)
- func Mask(number string, opts ...MaskOption) string
- func Normalize(number, region string) (string, error)
- func SupportedCountries() []string
- func ToLocal(number, region string) (string, error)
- type MaskOption
- type NormalizeResult
- type NumberType
- type ParseResult
- type Phone
- func (p *Phone) Country() string
- func (p *Phone) CountryCode() int
- func (p *Phone) E164() string
- func (p *Phone) Equal(other *Phone) bool
- func (p *Phone) Format(style Style) string
- func (p *Phone) ISO() string
- func (p *Phone) International() string
- func (p *Phone) InvalidReason() string
- func (p *Phone) IsFixedLine() bool
- func (p *Phone) IsMobile() bool
- func (p *Phone) IsPager() bool
- func (p *Phone) IsPossible() bool
- func (p *Phone) IsPremiumRate() bool
- func (p *Phone) IsTollFree() bool
- func (p *Phone) IsValid() bool
- func (p *Phone) IsVoIP() bool
- func (p *Phone) Local() string
- func (p Phone) MarshalJSON() ([]byte, error)
- func (p *Phone) Mask(opts ...MaskOption) string
- func (p *Phone) National() string
- func (p *Phone) NationalNumber() uint64
- func (p *Phone) NationalNumberString() string
- func (p *Phone) Operator() string
- func (p *Phone) RFC3966() string
- func (p *Phone) Raw() string
- func (p *Phone) Scan(src interface{}) error
- func (p *Phone) String() string
- func (p *Phone) Type() NumberType
- func (p *Phone) UnmarshalJSON(data []byte) error
- func (p Phone) Value() (driver.Value, error)
- type Style
- type ValidationResult
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Clean ¶
Clean strips every character that is not an ASCII digit, including any leading "+". It does not parse or validate the result -- it's a pure text-cleaning utility, useful as a first pass before Parse, or for sanitizing free-text input.
func Dedupe ¶
Dedupe normalizes every number in numbers (using defaultRegion for any that lack an explicit country code) and returns the unique E.164 forms, preserving the order of first appearance. Numbers that fail to parse are silently skipped -- use ValidateMany first if you need to know which inputs were dropped and why.
func Equal ¶
Equal reports whether two phone number strings refer to the same number, regardless of how each is formatted (local, E.164, spaced, punctuated, ...). An optional defaultRegion is used for either input that doesn't carry an explicit "+"/"00" country code, exactly as with Parse; if omitted, such inputs are compared as invalid (since they can't be unambiguously resolved to a country).
func Example ¶
Example returns a realistic sample E.164 phone number for the given ISO-3166-1 alpha-2 country, suitable for tests, fixtures, and demo data. It returns an error if the country isn't registered or has no example number configured.
n, _ := msisdn.Example("KE") // "+254712345678"
func Format ¶
Format parses number (optionally using region as the default country when number has no leading "+") and renders it using the requested Style. It's a convenience wrapper around Parse + Phone.Format for callers who don't need to keep the parsed Phone around.
msisdn.Format("0712345678", "KE", msisdn.E164) // "+254712345678"
func Mask ¶
func Mask(number string, opts ...MaskOption) string
Mask redacts the middle of a phone number for privacy-friendly logging, keeping a configurable number of leading and trailing digits visible. It operates on digits only (any "+", spaces, or punctuation in number are stripped first, matching Clean) and does not require the number to be valid or even parseable -- it's a text transform, not a parser.
msisdn.Mask("254712345678") // "2547******78"
msisdn.Mask("254712345678", msisdn.WithPrefixVisible(6)) // "254712****78"
func Normalize ¶
Normalize parses number (using region as the default country for numbers without a leading "+"/"00") and returns it as a bare digit string of calling-code + national number, with no "+", spaces, or other punctuation -- e.g. "254712345678". This is the canonical MSISDN form used as a storage/lookup key throughout telecom and fintech systems.
func SupportedCountries ¶
func SupportedCountries() []string
SupportedCountries returns the ISO codes of every registered country, including both "deep" (fully validated) and "shallow" (name/calling code only) entries.
Types ¶
type MaskOption ¶
type MaskOption func(*maskConfig)
MaskOption customizes Mask's behavior. See WithPrefixVisible, WithSuffixVisible, and WithMaskChar.
func WithMaskChar ¶
func WithMaskChar(r rune) MaskOption
WithMaskChar sets the character used to replace hidden digits. Default '*'.
func WithPrefixVisible ¶
func WithPrefixVisible(n int) MaskOption
WithPrefixVisible sets how many leading digits stay visible. Default 4.
func WithSuffixVisible ¶
func WithSuffixVisible(n int) MaskOption
WithSuffixVisible sets how many trailing digits stay visible. Default 2.
type NormalizeResult ¶
type NormalizeResult struct {
Input string `json:"input"`
Normalized string `json:"normalized,omitempty"`
Error error `json:"-"`
ErrorMessage string `json:"error,omitempty"`
}
NormalizeResult pairs a batch input with its normalized form (or error).
func NormalizeMany ¶
func NormalizeMany(numbers []string, defaultRegion string) []NormalizeResult
NormalizeMany runs Normalize over every number in numbers against defaultRegion.
type NumberType ¶
type NumberType int
NumberType classifies what kind of line a phone number belongs to.
const ( // Unknown means go-msisdn could not determine the number type, most // often because the country only has shallow support. Unknown NumberType = iota // Mobile is a mobile/cellular number. Mobile // FixedLine is a landline number. FixedLine // FixedLineOrMobile is used when the numbering range is shared // between mobile and fixed-line allocations and cannot be told // apart from the digits alone. FixedLineOrMobile // TollFree is a toll-free (freephone) number. TollFree // PremiumRate is a premium-rate number. PremiumRate // VoIP is a voice-over-IP number. VoIP // Pager is a pager number. Pager )
func (NumberType) MarshalJSON ¶
func (t NumberType) MarshalJSON() ([]byte, error)
MarshalJSON implements json.Marshaler so NumberType serializes as its string name (e.g. "MOBILE") rather than a bare integer.
type ParseResult ¶
type ParseResult struct {
Input string `json:"input"`
Phone *Phone `json:"phone,omitempty"`
Error error `json:"-"`
// ErrorMessage mirrors Error as a string for JSON consumers.
ErrorMessage string `json:"error,omitempty"`
}
ParseResult pairs a batch input with its parse outcome, so results can always be matched back to the original input by index -- important because Parse itself can fail per-item without aborting the batch.
func ParseMany ¶
func ParseMany(numbers []string, defaultRegion string) []ParseResult
ParseMany parses every number in numbers against defaultRegion, never stopping at the first failure. Check each result's Error/ErrorMessage to see which inputs failed and why.
type Phone ¶
type Phone struct {
// contains filtered or unexported fields
}
Phone represents a parsed phone number together with everything go-msisdn was able to determine about it: its country, national significant number, validity, type, and (where available) operator.
Phone is immutable and safe for concurrent use. The zero value is not usable; construct a Phone via Parse, ParseMany, or by decoding JSON / scanning from a database column.
func ExamplePhone ¶
ExamplePhone is like Example but returns a parsed *Phone.
func Parse ¶
Parse parses raw into a Phone.
If raw begins with "+" or "00" it is treated as already carrying an explicit country calling code and region is ignored. Otherwise region must be a supported ISO-3166-1 alpha-2 code (e.g. "KE") and raw is interpreted as a national/local number, with any domestic trunk prefix (e.g. a leading "0") stripped automatically.
Parse returns an error only for structural problems: an empty input, an unrecognized calling code, a missing/unknown region for a non-"+" number, or input that doesn't resemble a phone number at all. A number that parses structurally but fails validation (wrong length, unknown prefix range) is still returned, with Phone.IsValid() reporting false and Phone.InvalidReason() explaining why -- callers that want a hard error for invalid-but-parseable numbers should check IsValid() themselves, or use Validate.
func (*Phone) Country ¶
Country returns the country's display name, e.g. "Kenya". Returns "" for a zero-value Phone.
func (*Phone) CountryCode ¶
CountryCode returns the E.164 country calling code, e.g. 254.
func (*Phone) E164 ¶
E164 renders the number as "+<callingcode><nationalnumber>", e.g. "+254712345678". This is the canonical, comparison-safe form.
func (*Phone) Equal ¶
Equal reports whether two Phone values refer to the same number, compared by E.164 form.
func (*Phone) International ¶
International renders the number as "+<callingcode> <spaced national>", e.g. "+254 712 345678".
func (*Phone) InvalidReason ¶
InvalidReason returns a human-readable explanation of why the number is invalid, or "" if it is valid.
func (*Phone) IsFixedLine ¶
IsFixedLine reports whether Type() is FixedLine or FixedLineOrMobile.
func (*Phone) IsPossible ¶
IsPossible reports whether the number could plausibly be dialable -- i.e. it is not off by an implausible margin in length -- even if it isn't fully Valid (for example, correct length but an unrecognized prefix range). Every Valid number is also Possible.
func (*Phone) IsPremiumRate ¶
IsPremiumRate reports whether Type() is PremiumRate.
func (*Phone) IsTollFree ¶
IsTollFree reports whether Type() is TollFree.
func (*Phone) IsValid ¶
IsValid reports whether the number is fully valid: known country, correct length, and (for deeply-supported countries) a recognized number-type prefix range.
func (*Phone) Local ¶
Local returns the domestic dialling form without cosmetic spacing, e.g. "0712345678". This is what the project brief calls "local conversion": turning an international number back into the form a subscriber would dial domestically.
func (Phone) MarshalJSON ¶
MarshalJSON implements json.Marshaler, encoding the Phone as its E.164 string, e.g. "+254712345678". A zero-value Phone marshals to null.
func (*Phone) Mask ¶
func (p *Phone) Mask(opts ...MaskOption) string
Mask redacts the middle of the parsed number's E.164 digits. See the package-level Mask function for option documentation.
func (*Phone) National ¶
National renders the number in domestic dialling form, e.g. "0712 345678". If the country has no trunk prefix (e.g. NANP countries) this is the same as the spaced national significant number.
func (*Phone) NationalNumber ¶
NationalNumber returns the national significant number (no trunk prefix, no country code) as an unsigned integer, e.g. 712345678. Use NationalNumberString if you need to preserve leading zeros (rare, but possible for some countries' number ranges).
func (*Phone) NationalNumberString ¶
NationalNumberString returns the national significant number as a digit string, preserving any leading zeros.
func (*Phone) Operator ¶
Operator returns the detected mobile network operator name, e.g. "Safaricom", or "" if unknown (either because the country has no operator table registered, or no prefix rule matched).
func (*Phone) Scan ¶
Scan implements sql.Scanner, so a Phone (or *Phone) field on a struct can be populated directly from a database column via database/sql. The column value is parsed with Parse using "" as the region, so it must already be in E.164 form ("+254712345678") -- exactly what Value produces, which is what makes the pair round-trip safe.
func (*Phone) Type ¶
func (p *Phone) Type() NumberType
Type classifies the number (mobile, fixed line, toll free, ...). It returns Unknown for countries go-msisdn only shallowly supports, or if the number's prefix doesn't fall into a known range.
func (*Phone) UnmarshalJSON ¶
UnmarshalJSON implements json.Unmarshaler. It accepts a JSON string containing an E.164 number (e.g. "+254712345678"); a plain national number without a region hint cannot be unambiguously resolved from JSON alone and will produce an error. null decodes to the zero Phone.
type User struct {
Phone msisdn.Phone `json:"phone"`
}
type Style ¶
type Style int
Style identifies an output representation for a phone number.
Note on naming: the initial design brief called this type "Format" and asked for a top-level Format(number, STYLE) function. Go does not allow a type and a function to share an identifier in the same package, so the type is named Style here and the top-level function keeps the name Format -- exactly matching the requested call shape, msisdn.Format(n, msisdn.National), while staying compilable.
const ( // E164 is the "+254712345678" form: a plus sign, calling code, and // national significant number, with no other characters. E164 Style = iota // National is the domestic dialling form, e.g. "0712 345678". National // International is the E.164 digits with human-friendly spacing and // a leading "+", e.g. "+254 712 345678". International // RFC3966 is the "tel:+254712345678" URI form. RFC3966 )
type ValidationResult ¶
type ValidationResult struct {
// Valid is true if the number is fully valid.
Valid bool `json:"valid"`
// Possible is true if the number is at least plausible (right
// ballpark length), even if not fully Valid.
Possible bool `json:"possible"`
// Reason is a human-readable explanation, empty when Valid is true.
Reason string `json:"reason,omitempty"`
// Code is a stable, machine-readable reason code, empty when Valid
// is true. See the errors package for possible values.
Code msisdnerrors.Code `json:"code,omitempty"`
// Phone is the parsed number, or nil if parsing itself failed
// (e.g. empty input, unrecognized calling code, missing region).
Phone *Phone `json:"-"`
}
ValidationResult is the structured outcome of Validate: it tells you not just whether a number is valid, but why not.
func Validate ¶
func Validate(number, region string) ValidationResult
Validate parses number (see Parse for how region is used) and reports detailed validation information. Unlike Parse, Validate never returns a Go error -- structural parse failures are reported as an invalid ValidationResult instead, so this is the simplest entry point for "is this number OK, and if not, why?" checks such as form validation.
func ValidateMany ¶
func ValidateMany(numbers []string, defaultRegion string) []ValidationResult
ValidateMany runs Validate over every number in numbers against defaultRegion.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package errors defines the sentinel errors and structured error codes used throughout go-msisdn.
|
Package errors defines the sentinel errors and structured error codes used throughout go-msisdn. |
|
examples
|
|
|
basic
command
Command basic demonstrates the core go-msisdn API end to end.
|
Command basic demonstrates the core go-msisdn API end to end. |
|
Package operators provides a configurable, data-driven mobile network operator (MNO) lookup keyed by ISO-3166 country code and national significant number prefix.
|
Package operators provides a configurable, data-driven mobile network operator (MNO) lookup keyed by ISO-3166 country code and national significant number prefix. |