br

package module
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 11 Imported by: 0

README

Arandu

Arandu BR

The Brazilian values an Arandu application takes from a form and prints on a page: the CPF, the CNPJ (numeric and alphanumeric), the CEP, the mobile number, an amount in reais, a date, and the federative unit — and a CPF or a CNPJ with part of it hidden.

It is a library. It registers no route, owns no table and decides no authorization, so there is nothing to wire in bootstrap/app.go, nothing to construct, and no aru migrate to run. An application imports it and calls it.

Install

go get github.com/hyz-is/arandu-br
import br "github.com/hyz-is/arandu-br"

The module requires Hesape and nothing else. arandu.mod.toml declares no capability: no network, no filesystem, no process, no migration.

Validate a form

The package registers six rules with hesape/validation when it is initialized. Name them by their constants:

var StoreCustomer = validation.MustCompile(validation.Rules{
	"cpf":      "required|" + br.RuleCPF,
	"cnpj":     "nullable|" + br.RuleCNPJ,
	"document": "required|" + br.RuleCPFOrCNPJ,
	"postcode": "required|" + br.RuleCEP,
})
constant rule accepts
br.RuleCPF cpf a CPF, 00000000000 or 000.000.000-00
br.RuleCNPJ cnpj a CNPJ, 00000000000000 or 00.000.000/0000-00, letters allowed in the first twelve positions
br.RuleCPFOrCNPJ cpf_or_cnpj either of the two
br.RuleCEP cep a CEP, 00000000 or 00000-000
br.RuleMobile celular a mobile number, 00000000000, (00) 00000-0000 or (00)00000-0000, with a real area code and the leading 9
br.RuleBRL brl an amount in reais, as ParseBRL reads it

Write the constant, not the word it holds. A rule name exists once it is in the catalogue, and a rule set is compiled in a package-level variable, before main. Naming br.RuleCPF imports this package into the file that declares the set, and Go initializes an imported package before the variables of the one importing it, so the rules are registered before the set is compiled. The word "cpf" in a package that does not import this one may be compiled first, and then the application refuses to boot with an unknown rule.

Each rule checks what the matching Parse function checks, takes no argument (cpf:anything refuses every value) and only a string: a CPF sent as a JSON number has already lost its leading zeros. A blank value is left to required or nullable.

A failure reads is not a valid CPF (CNPJ, CPF or CNPJ, CEP, mobile number, amount in reais). An application that speaks Portuguese names its own sentence under validation.cpf, validation.cnpj, validation.cpf_or_cnpj, validation.cep, validation.celular and validation.brl in its translations, which hesape/validation reads before the default.

Take a value in

cpf, err := br.ParseCPF(in.String("cpf"))    // eleven digits, bare
cnpj, err := br.ParseCNPJ(in.String("cnpj")) // fourteen characters, bare, letters in capitals
cep, err := br.ParseCEP(in.String("postcode"))

Each Parse function returns the bare spelling, which is the one to store, or ErrInvalidCPF, ErrInvalidCNPJ or ErrInvalidCEP. ValidCPF, ValidCNPJ and ValidCEP answer the same question with a bool.

What is accepted is deliberately narrow: the value bare, or in its one conventional punctuation, and nothing else. No other separator, no separator out of place, no whitespace around it — a form that trimmed or re-punctuated input would accept a value the person did not type.

  • CPF — the two check digits the Receita Federal computes. The eleven repetitions of one digit compute too and belong to nobody, so they are refused by name.
  • CNPJ — the alphanumeric scheme: twelve digits or capital letters, each worth its ASCII code minus 48, then two numeric check digits. The numeric CNPJ is the all-digit case and is checked by the same computation. A lower-case letter is read as its capital. Fourteen repetitions of one character are refused.
  • CEP — eight digits, and not below 01000-000, where the Correios ranges begin. There is no check digit, so a CEP that passes may still address nothing.

None of them says whether a document was issued, is regular or exists: that is a question for the Receita Federal or the Correios, and this package makes no call.

CPFCheckDigits and CNPJCheckDigits compute the check digits of a base, which is what a seeder or a factory needs to write a valid document without borrowing somebody's.

An amount in reais
cents, err := br.ParseBRL(in.String("budget")) // int64 centavos, or ErrInvalidBRL

ParseBRL reads an amount as a person types it, and as an HTML number input submits it:

typed centavos
R$ 1.234,56, R$1.234,56, 1.234,56, 1234,56 123456
1.500 150000 — a dot followed by three digits groups thousands
1234.56, 1,5, 1.5 123456, 150, 150 — a dot followed by one or two digits is the decimal point
R$ 47, 0 4700, 0

Whitespace around the amount and after R$ is ignored. A sign, another currency, a space or a dot elsewhere among the digits, a group of other than three digits, a third decimal and an amount past the largest int64 are refused. Zero is an amount; a form that needs a positive one says so itself. A number input that takes centavos carries step="0.01", which keeps a third decimal — 1.500 meaning one and a half — out of what it submits.

Print a value

br.CPF("11122233344")      // "111.222.333-44", check digits or not
br.CNPJ("12abc34501de35")  // "12.ABC.345/01DE-35"
br.CEP("70040010")         // "70040-010"
br.BRL(123456)             // "R$ 1.234,56"
br.BRL(-99)                // "-R$ 0,99"
br.Date(t.In(saoPaulo))    // "31/12/2026"
br.DateTime(t.In(saoPaulo)) // "31/12/2026 15:04"

br.FormatBRL(123456, br.BRLFormat{WithoutGrouping: true}) // "R$ 1234,56"
br.FormatBRL(4700, br.BRLFormat{WithoutZeroCents: true})  // "R$ 47"
br.FormatBRL(19950, br.BRLFormat{WithoutZeroCents: true}) // "R$ 199,50"
br.FormatBRL(123456, br.BRLFormat{WithoutSymbol: true, WithoutGrouping: true}) // "1234,56", for a form field

br.BRLDecimal("1234.5678") // "R$ 1.234,5678", every digit kept

CPF, CNPJ and CEP punctuate a value of the right shape and return anything else unchanged: they format and do not validate, so a page that prints a stored value shows what is stored.

BRL takes centavos as an int64 — an amount that has to add up is held as an integer — and writes every one, the most negative included. It writes the same string as number.CurrencyFromCents(cents, "BRL") with the process-wide locale set to pt-BR, and depends on no process-wide setting.

FormatBRL is BRL departing from it in what its BRLFormat names, and the zero BRLFormat is BRL itself. Every amount it prints, ParseBRL reads back -- WithoutSymbol is how a form field is filled with an amount it hands back.

BRLDecimal writes an amount finer than a centavo -- a price per unit of usage, the exact total a charge was rounded from -- held as decimal text, the way math/big and a decimal column write it: the digits of the reais, then a dot and every digit of the fraction. Nothing is rounded, and a value that is not a decimal is returned unchanged.

Date writes the day t holds in its own location, and DateTime the day and the time of day, 31/12/2026 15:04. A time read from the database is usually in UTC, where a late evening in Brasília is already the next day, so convert it with t.In(location) first.

Hide part of a document

br.RedactCPF("12345678900", br.KeepCPFMiddle)      // "***.456.789-**"
br.RedactCPF("123.456.789-00", br.KeepCPFLastFive) // "***.***.789-00"
br.RedactCPF("12345678900", "•••.###.###-••")      // "•••.456.789-••"
br.RedactCNPJ("12ABC34501DE35", br.KeepCNPJEnds)   // "12.***.***/****-35"

A Redaction is spelled like the document: # shows the character in that position and every other character is written as it stands, the separators included. It has the length of the punctuated spelling or of the bare one, and the output takes that spelling.

redaction pattern prints
br.KeepCPFMiddle ***.###.###-** as the Portal da Transparência publishes a CPF
br.KeepCPFMiddleBare ***######** as the Receita Federal's open CNPJ data publishes a partner's CPF
br.KeepCPFCheckDigits ***.***.***-## only the two check digits, which identify nobody
br.KeepCPFLastFive ***.***.###-## what a profile page shows its owner
br.KeepCNPJEnds ##.***.***/****-## the first two and the last two characters

RedactCPF and RedactCNPJ read the value as ParseCPF and ParseCNPJ do, bare or punctuated, and do not check the check digits. Anything else — and a redaction of neither length — gives "", never the value: a redaction that fell back to its input would print what it exists to hide.

The federative units

br.UF is the closed set of the twenty-seven units, shaped like an enum aru make:enum writes:

br.UFSP.String()  // "SP"
br.UFSP.Label()   // "São Paulo"
uf, err := br.ParseUF(in.String("uf")) // exact code, in capitals, or ErrInvalidUF

br.UFValues() lists them in the alphabetical order of their names. The type satisfies enum.Enum, so the rest of the collection reads it without a second list:

enum.Options(br.UFValues()...)        // the options of a select
validation.EnumOf(br.UFValues()...)   // the rule

As a column, Value and Scan refuse a code outside the set.

What this package does not do

reached for why not
New, a Module, a line in k.Register there is nothing to register: no route, no table, no policy
a lookup at the Receita Federal or the Correios a validator that calls out is a validator that fails when the network does, and the manifest declares network = false
accepting 123.456.789 09, 01000-000 or full-width digits the caller would store a value the person did not type
a float64 amount BRL takes centavos; a float has already rounded
reading the process locale the same call would print differently depending on what another part of the application set

Layout

cpf.go, cnpj.go, cep.go   parsing, check digits and punctuation
mobile.go                 the mobile number
shape.go                  the masks they share
redact.go                 RedactCPF, RedactCNPJ and the Redaction type
rules.go                  the hesape/validation rules
money.go, date.go         BRL, FormatBRL, BRLDecimal, ParseBRL, Date and DateTime
uf.go                     the UF enum

Tests

GOWORK=off go test -race ./...

Every valid document in the suite is generated from a fixed seed by an oracle written apart from the package, from the Receita Federal's weight tables; none is copied from anywhere. The parsers are fuzzed against that oracle:

GOWORK=off go test -run='^$' -fuzz='^FuzzParseCNPJ$' -fuzztime=30s ./tests/Unit

Licence

MIT. See LICENSE.md. Copyright Paulo R. Lima.

Documentation

Overview

Package br validates and formats the Brazilian values an application takes from a form and prints on a page: the CPF, the CNPJ, the CEP, an amount in reais, a date, and the federative unit -- and a CPF or a CNPJ with part of it hidden.

It is a library. It registers no route, owns no table and decides no authorization, so nothing about it goes in bootstrap/app.go: a caller imports it and calls it.

Taking a value in

ParseCPF, ParseCNPJ and ParseCEP read a value written bare or in its one conventional punctuation, and return the bare spelling to store. ValidCPF, ValidCNPJ and ValidCEP are the same question answered with a bool. The CPF and the CNPJ are checked against the check digits the Receita Federal computes; the CNPJ may be alphanumeric.

ParseMobile reads a mobile number the same way. ParseBRL reads an amount in reais as a person types it, R$ 1.234,56, or as an HTML number input submits it, 1234.56, and returns centavos.

The same checks are rules of hesape/validation, registered when this package is initialized and named by RuleCPF, RuleCNPJ, RuleCPFOrCNPJ, RuleCEP, RuleMobile and RuleBRL:

var StoreCustomer = validation.MustCompile(validation.Rules{
	"document": "required|" + br.RuleCPFOrCNPJ,
	"postcode": "required|" + br.RuleCEP,
})

Printing a value

CPF, CNPJ, CEP and Mobile punctuate a stored value; BRL writes centavos as reais, R$ 1.234,56, and FormatBRL writes them without the grouping, without zero centavos or without the symbol; BRLDecimal writes an exact decimal amount finer than a centavo, every digit kept; Date writes a day as 31/12/2026 and DateTime a day and a time as 31/12/2026 15:04. RedactCPF and RedactCNPJ write a document with part of it hidden, through a Redaction such as KeepCPFMiddle, ***.456.789-**. Each is a function of its arguments alone.

UF is the closed set of the twenty-seven units, in the shape hesape/enum reads: UFValues, Label for the name a form shows, and Value and Scan for a column.

The files are laid out by subject:

cpf.go, cnpj.go, cep.go  -> parsing, check digits and punctuation
mobile.go                -> the mobile number
shape.go                 -> the masks they share
redact.go                -> RedactCPF, RedactCNPJ and Redaction
rules.go                 -> the hesape/validation rules
money.go, date.go        -> BRL, FormatBRL, BRLDecimal, ParseBRL, Date and DateTime
uf.go                    -> the UF enum

Index

Constants

View Source
const (
	// RuleCPF is a CPF, as ParseCPF accepts it.
	RuleCPF = "cpf"
	// RuleCNPJ is a CNPJ, numeric or alphanumeric, as ParseCNPJ accepts it.
	RuleCNPJ = "cnpj"
	// RuleCPFOrCNPJ is a value either ParseCPF or ParseCNPJ accepts: the
	// document field of a form a person or a company fills in.
	RuleCPFOrCNPJ = "cpf_or_cnpj"
	// RuleCEP is a CEP, as ParseCEP accepts it.
	RuleCEP = "cep"
	// RuleMobile is a Brazilian mobile number, as ParseMobile accepts it.
	RuleMobile = "celular"
	// RuleBRL is an amount in reais, as ParseBRL accepts it: the price or the
	// budget field of a form.
	RuleBRL = "brl"
)

The names this package registers with hesape/validation, for a rule string:

var StoreCustomer = validation.MustCompile(validation.Rules{
	"document": "required|" + br.RuleCPFOrCNPJ,
	"postcode": "required|" + br.RuleCEP,
})

Write the constant rather than the name it holds. A rule name is real only once it is in the catalogue, and the catalogue is filled when this package is initialized: a rule set that names the constant imports the package, and Go initializes an imported package before the importer's own variables, so the set is compiled after the rules exist. A rule set that spells "cpf" in a package that does not import this one may be compiled first, and then it fails at boot with an unknown rule.

Each rule takes no argument; one written after a colon refuses every value, because an argument this package would ignore is a typo nothing reports. Each accepts what the matching Parse function accepts, and only a string: a CPF sent as a JSON number has already lost its leading zeros. A blank value is not checked -- write required, or nullable, beside the rule for that.

Variables

View Source
var ErrInvalidBRL = errors.New("br: not a valid amount in reais")

ErrInvalidBRL is what ParseBRL returns for a value that is not an amount in reais.

View Source
var ErrInvalidCEP = errors.New("br: not a valid CEP")

ErrInvalidCEP is what ParseCEP returns for a value that is not a CEP.

View Source
var ErrInvalidCNPJ = errors.New("br: not a valid CNPJ")

ErrInvalidCNPJ is what ParseCNPJ and CNPJCheckDigits return for a value that is not a CNPJ.

View Source
var ErrInvalidCPF = errors.New("br: not a valid CPF")

ErrInvalidCPF is what ParseCPF and CPFCheckDigits return for a value that is not a CPF. It says nothing about which part was wrong, because the person who typed the value is the only one who can tell a typo from a wrong number.

View Source
var ErrInvalidMobile = errors.New("br: not a valid mobile number")

ErrInvalidMobile is what ParseMobile returns for a value that is not a Brazilian mobile number.

View Source
var ErrInvalidUF = errors.New("br: not a UF")

ErrInvalidUF is what ParseUF, Value and Scan return for a code outside the set.

Functions

func BRL

func BRL(cents int64) string

BRL writes an amount of reais held as a count of centavos, the way a Brazilian page prints money: R$ 1.234,56.

A dot separates each three digits of the reais, a comma stands before the two digits of the centavos, and the symbol leads with a space after it. A negative amount leads with the sign, before the symbol -- -R$ 1.234,56 -- because a sign written after the symbol reads as part of the amount. Zero is R$ 0,00, and every int64 is written, its most negative value included.

The amount is an integer because an amount that has to add up is held as one; no float64 appears on the way from it to the page. The result depends on nothing but the argument: hesape/number writes the same string from CurrencyFromCents(cents, "BRL") only while the process-wide locale is pt-BR, and a library cannot set that locale without setting it for everything else the application formats.

BRL is FormatBRL with the zero BRLFormat.

func BRLDecimal added in v0.4.0

func BRLDecimal(amount string) string

BRLDecimal writes an exact amount of reais held as decimal text -- the digits of the reais, then a dot and as many digits of a fraction of a real as the amount has, the way math/big and a decimal column write one -- with the symbol, the grouping and the comma of BRL, and every digit of the fraction kept: 1234.5678 is R$ 1.234,5678, -0.000001 is -R$ 0,000001 and 47 is R$ 47.

It is for an amount finer than a centavo -- a price per unit of usage, the exact total a charge was rounded from -- that a page must show to the last digit it was computed to. Nothing is rounded and no float64 appears on the way: the digits that arrive are the digits written.

The amount is an optional minus sign, one ASCII digit or more, and optionally a dot followed by one digit or more. Anything else is returned unchanged: it formats, and does not validate.

func CEP

func CEP(s string) string

CEP writes a CEP punctuated, as 00000-000.

It takes the eight digits bare or already punctuated, and returns anything else unchanged: it formats, and does not validate. Validate with ParseCEP where the value is taken in.

func CNPJ

func CNPJ(s string) string

CNPJ writes a CNPJ punctuated, as 00.000.000/0000-00, with its letters in capitals.

It takes the fourteen characters bare or already punctuated, and returns anything else unchanged: it formats, and does not validate. Validate with ParseCNPJ where the value is taken in.

func CNPJCheckDigits

func CNPJCheckDigits(base string) (string, error)

CNPJCheckDigits returns the two check digits of a CNPJ whose first twelve characters are base, and ErrInvalidCNPJ when base is not twelve digits or letters. A lower-case letter is read as its capital.

Each character is worth its ASCII code minus 48 -- a digit its own value, A seventeen, Z forty-two. A check digit is the sum of the characters before it, weighted from the right by 2 to 9 and again from 2, taken modulo eleven: a remainder below two gives zero, and any other gives eleven minus it.

func CPF

func CPF(s string) string

CPF writes a CPF punctuated, as 000.000.000-00.

It takes the eleven digits bare or already punctuated, and returns anything else unchanged: it formats, and does not validate, so a page that prints a stored value shows what is stored rather than an empty cell. Validate with ParseCPF where the value is taken in.

func CPFCheckDigits

func CPFCheckDigits(base string) (string, error)

CPFCheckDigits returns the two check digits of a CPF whose first nine digits are base, and ErrInvalidCPF when base is not nine digits.

Each check digit is the sum of the digits before it, weighted from 10 (or 11) down to 2, times ten, modulo eleven -- with ten written as zero. It is what a seeder or a factory needs to write a CPF that passes, without borrowing one that belongs to somebody.

func Date

func Date(t time.Time) string

Date writes the calendar day of t as a Brazilian page prints it: 31/12/2026, day, month and four-digit year.

The day is the one t holds in its own location. An instant read from a database is usually in UTC, where a late evening in Brasília is already the next day, so convert it first -- br.Date(t.In(location)) -- with the location the reader lives in.

func DateTime added in v0.4.0

func DateTime(t time.Time) string

DateTime writes the calendar day and the time of day of t as a Brazilian page prints them: 31/12/2026 15:04, the day as Date writes it, a space, and the hours and minutes on a twenty-four hour clock.

Like Date it reads t in its own location, so an instant from a database is converted first -- br.DateTime(t.In(location)) -- with the location the reader lives in, and a page that keeps UTC says so beside it.

func FormatBRL added in v0.3.0

func FormatBRL(cents int64, f BRLFormat) string

FormatBRL writes an amount of reais held as a count of centavos, as BRL does, departing from it in what f says: R$ 1234,56 without the grouping, R$ 47 without the zero centavos, 1.234,56 without the symbol. The sign and the comma are BRL's, and every int64 is written.

func Mobile added in v0.2.0

func Mobile(s string) string

Mobile writes a mobile number punctuated, as (00) 00000-0000.

It takes the eleven digits bare or already punctuated, and returns anything else unchanged: it formats, and does not validate. Validate with ParseMobile where the value is taken in.

func ParseBRL added in v0.3.0

func ParseBRL(s string) (int64, error)

ParseBRL reads an amount in reais as a person types it into a form, and returns it as a count of centavos, or ErrInvalidBRL.

The amount may be led by the symbol, R$, with or without a space after it, and whitespace around the whole is ignored. The reais are digits, bare (1234) or grouped by dots in threes (1.234); a comma then gives one or two digits of centavos (1.234,56, and 1.234,5 for fifty centavos). An amount with no comma may instead give its centavos after a single dot, when that dot is followed by one or two digits and nothing else (1234.56): that is how an HTML number input submits a value, and no grouping of thousands leaves fewer than three digits after a dot. A dot followed by three digits always groups thousands, so 1.500 is fifteen hundred reais -- a number input that should take centavos says step="0.01", which keeps a third decimal out of it.

Everything else is refused: a sign, another currency or a lower-case r$, a space or a dot inside the digits other than as above, a group of other than three digits, a third digit of centavos, a comma with nothing after it, a digit outside ASCII, and an amount past the largest int64. Zero is an amount; a form that needs a positive one says so itself.

func ParseCEP

func ParseCEP(s string) (string, error)

ParseCEP returns the eight digits of a CEP, written bare (00000000) or punctuated (00000-000), and ErrInvalidCEP for anything else or for a code below 01000-000, where no range begins.

A CEP carries no check digit, so a code that passes may still address nothing: only a lookup in the Correios base can say it exists.

The digits come back bare, which is the spelling to store.

func ParseCNPJ

func ParseCNPJ(s string) (string, error)

ParseCNPJ returns the fourteen characters of a CNPJ, written bare (00000000000000) or punctuated (00.000.000/0000-00), and ErrInvalidCNPJ for anything else.

The first twelve positions may hold letters as well as digits: that is the alphanumeric CNPJ the Receita Federal issues, and the numeric CNPJ is the case of it whose twelve positions are all digits, checked by the same computation. The last two positions are the check digits, and are always digits. A letter typed in lower case is read as the capital it stands for, and comes back as one.

It refuses fourteen repetitions of one character, which no CNPJ is. It does not say whether the CNPJ was issued or is active: only the Receita Federal can.

The characters come back bare, which is the spelling to store.

func ParseCPF

func ParseCPF(s string) (string, error)

ParseCPF returns the eleven digits of a CPF, written bare (00000000000) or punctuated (000.000.000-00), and ErrInvalidCPF for anything else.

It checks the shape and the two check digits the Receita Federal computes, and refuses the eleven repetitions of one digit, whose check digits compute but which belong to nobody. It does not say whether the CPF was issued or is regular: only the Receita Federal can.

The digits come back bare, which is the spelling to store: a column that holds both spellings cannot be searched for either.

func ParseMobile added in v0.2.0

func ParseMobile(s string) (string, error)

ParseMobile returns the eleven digits of a Brazilian mobile number, written bare (00000000000) or punctuated ((00) 00000-0000, or (00)00000-0000 without the space after the area code, as it is often typed), and ErrInvalidMobile for anything else.

It checks the shape, that the area code is one Anatel assigns, that the number starts with 9 (every mobile number since 2016), and refuses the nine followed by eight zeros, which a form fills when somebody types nothing. It does not say whether the line exists: only the operator can.

The digits come back bare, which is the spelling to store.

func RedactCNPJ added in v0.3.0

func RedactCNPJ(s string, r Redaction) string

RedactCNPJ writes a CNPJ with the positions r hides replaced, as r spells it.

It takes the fourteen characters bare or punctuated, as ParseCNPJ reads them, a lower-case letter shown as its capital, and does not check the check digits. For anything else, or a redaction of neither length, it returns "".

func RedactCPF added in v0.3.0

func RedactCPF(s string, r Redaction) string

RedactCPF writes a CPF with the positions r hides replaced, as r spells it.

It takes the eleven digits bare or punctuated, as ParseCPF reads them, and does not check the check digits: a page that hides a stored value hides it whether or not it was ever valid. For anything else -- a value of another shape, or a redaction of neither length -- it returns "", and never the value it was given: a redaction that fell back to its input would print the document it exists to hide.

func ValidBRL added in v0.3.0

func ValidBRL(s string) bool

ValidBRL reports whether ParseBRL accepts s.

func ValidCEP

func ValidCEP(s string) bool

ValidCEP reports whether ParseCEP accepts s.

func ValidCNPJ

func ValidCNPJ(s string) bool

ValidCNPJ reports whether ParseCNPJ accepts s.

func ValidCPF

func ValidCPF(s string) bool

ValidCPF reports whether ParseCPF accepts s.

func ValidMobile added in v0.2.0

func ValidMobile(s string) bool

ValidMobile reports whether ParseMobile accepts s.

Types

type BRLFormat added in v0.3.0

type BRLFormat struct {
	// WithoutGrouping writes the reais with no dot between their thousands:
	// R$ 1234,56.
	WithoutGrouping bool
	// WithoutZeroCents leaves the centavos off an amount of whole reais, the
	// way a price list writes one: R$ 47, and still R$ 199,50.
	WithoutZeroCents bool
	// WithoutSymbol leaves the R$ and the space after it off, the way a form
	// field holds an amount it hands back to the person: 1.234,56, and
	// -1.234,56 for a negative one. ParseBRL reads it back.
	WithoutSymbol bool
}

BRLFormat is how FormatBRL departs from BRL. Its zero value departs in nothing, so each field names what it leaves out.

type Redaction added in v0.3.0

type Redaction string

A Redaction is how a page writes a document with part of it hidden, spelled the way the document is spelled: '#' shows the character in that position, and every other character is written as it stands.

"***.###.###-**"  the fourth to the ninth digits of a CPF, punctuated
"***######**"     the same digits, bare
"•••.###.###-••"  the same digits, hidden behind bullets

A Redaction has the length, in characters, of either spelling of the document: the punctuated one (14 for a CPF, 18 for a CNPJ) or the bare one (11 and 14). Where the punctuated spelling holds a separator, the redaction writes its own character there, so it chooses the punctuation as well as the hiding. The length alone says which spelling a redaction is, so one written for a document of another kind is read as whichever of the two it measures, or refused.

The named redactions are the ones Brazilian sources publish and pages print. A redaction written as a literal is just as good: any string of one of the two lengths is one.

const (
	// KeepCPFMiddle shows the fourth to the ninth digits of a CPF, punctuated:
	// ***.456.789-**. It is how the Portal da Transparência publishes the CPF
	// of a public agent.
	KeepCPFMiddle Redaction = "***.###.###-**"
	// KeepCPFMiddleBare shows the same six digits with no punctuation:
	// ***456789**. It is how the Receita Federal's open CNPJ data publishes the
	// CPF of a partner.
	KeepCPFMiddleBare Redaction = "***######**"
	// KeepCPFCheckDigits shows only the two check digits of a CPF, which
	// identify nobody: ***.***.***-00.
	KeepCPFCheckDigits Redaction = "***.***.***-##"
	// KeepCPFLastFive shows the last five digits of a CPF, as a profile page
	// reminds its owner which CPF it holds: ***.***.789-00.
	KeepCPFLastFive Redaction = "***.***.###-##"
	// KeepCNPJEnds shows the first two and the last two characters of a CNPJ:
	// 12.***.***/****-35.
	KeepCNPJEnds Redaction = "##.***.***/****-##"
)

The redactions a page usually needs. Each is a constant of the type, so a call reads br.RedactCPF(cpf, br.KeepCPFMiddle).

type UF

type UF string

UF is one of the twenty-seven federative units of Brazil -- the twenty-six states and the Federal District -- stored as its two-letter code.

It is a closed set in the shape a generated enum has: constants that are the only valid values, Valid to ask, Label for what a form shows, and a Value/Scan pair that refuses a code outside the set on the way to and from a column. So hesape/enum reads it like any other: enum.Options(br.UFValues()...) fills a select, and validation.EnumOf(br.UFValues()...) is the rule.

const (
	UFAC UF = "AC"
	UFAL UF = "AL"
	UFAP UF = "AP"
	UFAM UF = "AM"
	UFBA UF = "BA"
	UFCE UF = "CE"
	UFDF UF = "DF"
	UFES UF = "ES"
	UFGO UF = "GO"
	UFMA UF = "MA"
	UFMT UF = "MT"
	UFMS UF = "MS"
	UFMG UF = "MG"
	UFPA UF = "PA"
	UFPB UF = "PB"
	UFPR UF = "PR"
	UFPE UF = "PE"
	UFPI UF = "PI"
	UFRJ UF = "RJ"
	UFRN UF = "RN"
	UFRS UF = "RS"
	UFRO UF = "RO"
	UFRR UF = "RR"
	UFSC UF = "SC"
	UFSP UF = "SP"
	UFSE UF = "SE"
	UFTO UF = "TO"
)

The units, in the alphabetical order of their names, which is the order a list of them is read in. Stored exactly as written: the code is what the Correios, the Receita Federal and IBGE all print.

func ParseUF

func ParseUF(s string) (UF, error)

ParseUF turns request input into a UF, or wraps ErrInvalidUF.

It reads the code exactly as the set spells it, in capitals: the value a select sends back is the one Options gave it, and a value that differs from every option did not come from the form.

func UFValues

func UFValues() []UF

UFValues lists the twenty-seven units in declaration order.

It is what fills a select and what a rule is built from, so the set is written once, here, and every list of units derives from it.

func (UF) Label

func (v UF) Label() string

Label is the name of the unit, which is what a form shows: São Paulo for SP. It is empty for a code outside the set.

It is separate from String on purpose. The code is a contract with every column and every message that holds it; the name is a contract with nobody, and changing how one is spelled must not be able to change a row.

func (*UF) Scan

func (v *UF) Scan(src any) error

Scan implements sql.Scanner. A code the set does not hold is an error at the row that has it, rather than a value that behaves like a unit three layers up.

func (UF) String

func (v UF) String() string

String is the code, so fmt and a view print it unchanged.

func (UF) Valid

func (v UF) Valid() bool

Valid reports whether v is one of the units.

func (UF) Value

func (v UF) Value() (driver.Value, error)

Value implements driver.Valuer. It refuses a code outside the set, which is what keeps a zero-valued struct from putting an empty string in the column.

Jump to

Keyboard shortcuts

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