Help us shape the future of Go! Take the 2026 Go Developer Survey

aut2fa

package module
v0.1.0 Latest Latest
Warning

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

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

README

aut2fa-go

Biblioteca cliente (SDK) de Go para enviar, consultar e verificar códigos 2FA pela API aut2fa.

Requer Go 1.22 ou superior. Usa apenas a biblioteca padrão do Go. Licença MIT.

Instalação

Instale a versão 0.1.0 no seu módulo:

go get github.com/jhowbhz/aut2fa-go@v0.1.0

Enviar, consultar e verificar

Crie o cliente com a chave da aplicação e use o ID retornado para consultar ou verificar o envio:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/jhowbhz/aut2fa-go"
)

func main() {
	client, err := aut2fa.New(os.Getenv("AUT2FA_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	ctx := context.Background()
	send, err := client.Send(ctx, aut2fa.SendParams{
		To: "+5511999999999",
		Code: "123456",
		Locale: "pt-BR",
		IdempotencyKey: "cadastro-user-123",
	})
	if err != nil {
		log.Fatal(err)
	}

	status, err := client.Status(ctx, send.ID)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(send.ID, status.Status)

	verification, err := client.Verify(ctx, send.ID, "123456")
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(verification.Valid, verification.AttemptsLeft)
}

To é obrigatório. Code e Locale são opcionais no envio; deixe Code vazio para a API gerar o código. A chave de idempotência é opcional, fica somente no header Idempotency-Key e aceita até 255 bytes sem caracteres de controle. Use uma chave por operação lógica e preserve a mesma chave e o mesmo corpo ao repetir essa operação.

Send e Status retornam *aut2fa.SendResponse. Verify retorna *aut2fa.VerifyResponse. Um resultado com Valid == false e HTTP 200 é uma tentativa de verificação normal.

Campos nullable são ponteiros (*string ou *time.Time); um null da API vira nil. O SDK decodifica timestamps como time.Time e aceita campos adicionais do JSON.

O exemplo completo usa AUT2FA_API_KEY, AUT2FA_TO e, opcionalmente, AUT2FA_IDEMPOTENCY_KEY. Rode go run ./examples/basic com essas variáveis definidas para fazer chamadas reais. Os testes usam servidores locais e não enviam mensagens.

Configuração

Substitua a construção do cliente abaixo e acrescente os imports net/http e time ao seu programa:

client, err := aut2fa.New(os.Getenv("AUT2FA_API_KEY"),
	aut2fa.WithBaseURL("http://localhost:8080"),
	aut2fa.WithTimeout(5*time.Second),
	aut2fa.WithHTTPClient(&http.Client{}),
)

A base padrão é https://api.aut2fa.com, com timeout total de 10 segundos por chamada. WithTimeout exige duração positiva. A URL precisa ser HTTP ou HTTPS, com host e sem credenciais, query ou fragmento; também pode conter um prefixo de caminho. IDs aceitam apenas letras ASCII, números, _ e -. Credenciais vazias ou com caracteres de controle são rejeitadas ao construir o cliente.

WithHTTPClient copia o cliente fornecido e preserva seu transporte e cookie jar. O timeout do SDK e a proibição de redirects prevalecem sobre os valores do cliente fornecido, sem modificá-lo. O SDK clona transportes padrão e desativa keep-alive para impedir retries transparentes em conexões reutilizadas. Um transporte personalizado deve implementar http.RoundTripper sem retries e ser seguro para uso concorrente.

O SDK não segue redirects e não faz retries automáticos. Cada método aceita context.Context; cancelamentos e deadlines do chamador são preservados. O cliente pode ser compartilhado entre goroutines.

Erros

Após uma chamada, importe errors e identifique a rejeição HTTP ou uma resposta inválida:

var problem *aut2fa.ApiError
if errors.As(err, &problem) {
	fmt.Println(problem.Status, problem.Code, problem.Detail)
	fmt.Println(problem.Errors, problem.RetryAfter)
}
if errors.Is(err, aut2fa.ErrInvalidResponse) {
	fmt.Println("A API retornou uma resposta inválida.")
}

Respostas HTTP fora de 2xx geram *ApiError com o status HTTP real, Code, Detail, Errors e o RetryAfter bruto. O header pode conter segundos ou uma data HTTP. Corpos de erro inesperados usam http_error; o SDK não expõe o corpo arbitrário.

Respostas 2xx inválidas são identificadas por ErrInvalidResponse. Identifique timeouts do cliente com errors.As para net.Error e seu método Timeout(). Cancelamentos e deadlines do contexto do chamador preservam context.Canceled e context.DeadlineExceeded, verificáveis com errors.Is.

Desenvolvimento

Valide a biblioteca e o exemplo sem acessar a API real:

gofmt -w .
go vet ./...
go test -race ./...
go build ./...

A CI valida formatação, vet, testes com race detector e build no Linux, com Go 1.22 e a versão estável. Não há workflow de publicação automática. A versão Go é distribuída pela tag Git v0.1.0 após revisão.

Consulte a documentação da API aut2fa para o contrato HTTP.

Documentation

Overview

Package aut2fa sends and verifies 2FA codes through the public aut2fa API.

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidResponse = errors.New("aut2fa: invalid API response")

ErrInvalidResponse identifies malformed or incomplete successful responses.

Functions

This section is empty.

Types

type ApiError

type ApiError struct {
	Status     int
	Code       string
	Detail     string
	Errors     map[string]string
	RetryAfter string
}

ApiError preserves an HTTP rejection and its RFC 9457 problem details. RetryAfter is the raw Retry-After header, which may be seconds or an HTTP date.

func (*ApiError) Error

func (err *ApiError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client uses one immutable application key and configuration across requests. Create it with New; it can be shared by concurrent goroutines.

func New

func New(apiKey string, options ...Option) (*Client, error)

New validates credentials and applies options before creating the client.

func (*Client) Send

func (c *Client) Send(ctx context.Context, params SendParams) (*SendResponse, error)

Send creates a delivery. An idempotency key is sent only as an HTTP header.

func (*Client) Status

func (c *Client) Status(ctx context.Context, id string) (*SendResponse, error)

Status fetches the current delivery and verification state.

func (*Client) Verify

func (c *Client) Verify(ctx context.Context, id, code string) (*VerifyResponse, error)

Verify checks a code once; Valid=false is a normal successful result.

type Option

type Option func(*configuration) error

Option configures a Client before it is created.

func WithBaseURL

func WithBaseURL(baseURL string) Option

WithBaseURL sets an absolute HTTP(S) URL, optionally with a path prefix. Credentials, queries and fragments are not accepted.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient preserves an injected client's transport and cookie jar. The SDK copies the client and enforces its own timeout and redirect policy. Standard transports are cloned with keep-alives disabled to prevent retries.

func WithTimeout

func WithTimeout(timeout time.Duration) Option

WithTimeout sets the total request timeout, including reading the response. The duration must be positive; the default is ten seconds.

type SendParams

type SendParams struct {
	To             string `json:"to"`
	Code           string `json:"code,omitempty"`
	Locale         string `json:"locale,omitempty"`
	IdempotencyKey string `json:"-"`
}

SendParams carries a destination and optional code, locale and idempotency key. An empty Code lets the API generate a code; an empty Locale uses its default.

type SendResponse

type SendResponse struct {
	ID            string     `json:"id"`
	Status        string     `json:"status"`
	Verification  string     `json:"verification"`
	Mode          string     `json:"mode"`
	Channel       *string    `json:"channel"`
	From          *string    `json:"from"`
	ExpiresAt     time.Time  `json:"expires_at"`
	CreatedAt     time.Time  `json:"created_at"`
	SentAt        *time.Time `json:"sent_at"`
	DeliveredAt   *time.Time `json:"delivered_at"`
	ReadAt        *time.Time `json:"read_at"`
	VerifiedAt    *time.Time `json:"verified_at"`
	FailedAt      *time.Time `json:"failed_at"`
	FailureReason *string    `json:"failure_reason"`
}

SendResponse preserves JSON nulls as nil pointers and timestamps as time.Time. State strings remain open to values added by future API versions.

type VerifyResponse

type VerifyResponse struct {
	Valid        bool   `json:"valid"`
	Verification string `json:"verification"`
	AttemptsLeft int    `json:"attempts_left"`
}

VerifyResponse records one verification attempt, including an invalid code.

Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

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