SDK Go
SDK oficial para Go 1.21+ com tipagem forte, zero dependências externas e suporte nativo a context.
Instalação
bash
go get github.com/cpfhub/cpfhub-goRequerimentos: Go 1.21+
Inicialização
Go
package main
import (
"github.com/cpfhub/cpfhub-go/cpfhub"
)
func main() {
client := cpfhub.New(cpfhub.Config{
APIKey: os.Getenv("CPFHUB_API_KEY"),
// Timeout: 10 * time.Second, // opcional
})
}Opções de configuração
| Campo | Tipo | Padrão | Descrição |
|---|---|---|---|
APIKey | string | - | Sua API Key (obrigatório) |
Timeout | time.Duration | 10s | Timeout da requisição |
BaseURL | string | https://api.cpfhub.io | URL base da API |
Métodos
client.Lookup(ctx, cpf)
Consulta um CPF e retorna os dados de identidade.
Go
ctx := context.Background()
result, err := client.Lookup(ctx, "12345678909")
if err != nil {
// tratar erro
}
fmt.Println(result.Data.Name)Retorno: (*CPFHubResult, error)
Go
type CPFHubResult struct {
Success bool `json:"success"`
Data CPFData `json:"data"`
}
type CPFData struct {
CPF string `json:"cpf"`
Name string `json:"name"`
NameUpper string `json:"nameUpper"`
Gender string `json:"gender"` // "M" ou "F"
BirthDate string `json:"birthDate"` // "DD/MM/AAAA"
Day int `json:"day"`
Month int `json:"month"`
Year int `json:"year"`
}Tratamento de erros
Go
import "github.com/cpfhub/cpfhub-go/cpfhub"
result, err := client.Lookup(ctx, "12345678909")
if err != nil {
var e *cpfhub.Error
if errors.As(err, &e) {
fmt.Println(e.Code) // "CPF_NOT_FOUND"
fmt.Println(e.Message) // "CPF not found in our database"
fmt.Println(e.StatusCode) // 404
}
}Códigos de erro
e.Code | e.StatusCode | Descrição |
|---|---|---|
CPF_NOT_FOUND | 404 | CPF não encontrado (sem consumo de crédito) |
INVALID_CPF_FORMAT | 400 | Formato inválido |
INVALID_CPF_DIGITS | 422 | Dígitos verificadores inválidos |
MISSING_API_KEY | 401 | API Key ausente |
INVALID_API_KEY | 401 | API Key inválida |
RATE_LIMIT_EXCEEDED | 429 | Limite de taxa excedido |
INSUFFICIENT_CREDITS | 403 | Sem créditos disponíveis |
Exemplos de integração
Gin
Go
package main
import (
"net/http"
"errors"
"github.com/gin-gonic/gin"
"github.com/cpfhub/cpfhub-go/cpfhub"
)
var client = cpfhub.New(cpfhub.Config{APIKey: os.Getenv("CPFHUB_API_KEY")})
func main() {
r := gin.Default()
r.GET("/cpf/:cpf", func(c *gin.Context) {
result, err := client.Lookup(c.Request.Context(), c.Param("cpf"))
if err != nil {
var e *cpfhub.Error
if errors.As(err, &e) {
c.JSON(e.StatusCode, gin.H{"error": e.Code})
return
}
c.JSON(http.StatusInternalServerError, gin.H{"error": "INTERNAL_ERROR"})
return
}
c.JSON(http.StatusOK, result.Data)
})
r.Run(":8080")
}net/http padrão
Go
func cpfHandler(w http.ResponseWriter, r *http.Request) {
cpf := r.PathValue("cpf")
result, err := client.Lookup(r.Context(), cpf)
if err != nil {
var e *cpfhub.Error
if errors.As(err, &e) {
http.Error(w, e.Code, e.StatusCode)
return
}
http.Error(w, "internal error", 500)
return
}
json.NewEncoder(w).Encode(result.Data)
}Repositório e suporte
- github.com/cpfhub/cpfhub-go - código-fonte, issues e contribuições
- pkg.go.dev/github.com/cpfhub/cpfhub-go - documentação de referência
Atualizado em 12 de maio de 2026