Vai al contenuto

SDK

SDK per Go

github.com/deveryidea/voaaro-go v0.4.0 per Go 1.21 e successivi: solo libreria standard, le stesse chiamate di resend-go, tentativi automatici e iteratori Iter[T].

Installazione

Shell
go get github.com/deveryidea/voaaro-go@latest

Versione 0.4.0. Go 1.21 o successivo, nessuna dipendenza (libreria standard). Pacchetto voaaro.

Configurazione

Go
import "github.com/deveryidea/voaaro-go"

client := voaaro.NewClient(os.Getenv("VOAARO_API_KEY"),
	voaaro.WithBaseURL("https://mail.example.com"),
	voaaro.WithMaxRetries(2)) // default; 0: no retry and no idempotency key drawn

Opzioni: WithBaseURL, WithMaxRetries, WithHTTPClient, WithUserAgent, WithHeader. Timeout predefinito: 60 secondi. Indica sempre l'indirizzo della tua istanza con WithBaseURL (o VOAARO_BASE_URL).

Invio

Go
pdf, _ := os.ReadFile("guide.pdf")

sent, err := client.Emails.SendWithOptions(ctx, &voaaro.SendEmailRequest{
	From:        "Acme <notifications@example.com>",
	To:          []string{"client@example.org"},
	Subject:     "Welcome",
	Html:        "<p>Your account is ready.</p>",
	Attachments: []*voaaro.Attachment{{Filename: "guide.pdf", Content: pdf}}, // raw bytes
}, &voaaro.SendEmailOptions{IdempotencyKey: "welcome-42"})
if err != nil {
	var apiErr *voaaro.Error
	if errors.As(err, &apiErr) {
		log.Println(apiErr.StatusCode, apiErr.Name, apiErr.Message, apiErr.RetryAfter)
	}
	return err
}
log.Println(sent.Id)

Ogni metodo esiste anche nella forma …WithContext(ctx, …).

Tentativi automatici e idempotenza

  • L'SDK ripete da solo una richiesta dopo un errore di rete, un 429 rate_limit_exceeded o un 500, 502, 503, 504: 2 tentativi per impostazione predefinita (WithMaxRetries(n)). Mai dopo daily_quota_exceeded né dopo un altro errore 4xx. Attesa: Retry-After (al massimo 60 secondi), altrimenti 0,5 s × 2^n con una componente casuale, al massimo 8 secondi; l'annullamento del context interrompe l'attesa.
  • Ogni richiesta di creazione ha un campo IdempotencyKey (CreateContactRequest, CreateWebhookRequest, AddSuppressionRequest, CreateFormRequest…); per qualsiasi altro POST, usa voaaro.WithIdempotencyKey(ctx, chiave) con la variante WithContext.
  • Senza chiave, e finché i tentativi automatici sono consentiti, l'SDK genera un UUID v4 per ogni POST, lo stesso da un tentativo all'altro.
Go
ctx := voaaro.WithIdempotencyKey(context.Background(), "cancel-broadcast-42")
client.Broadcasts.CancelWithContext(ctx, broadcastId)

Paginazione

Ogni elenco con cursore ha un iteratore Iter[T] (senza range-over-func, per Go 1.21):

Go
it := client.Contacts.ListAll(ctx, &voaaro.ListContactsOptions{SegmentId: segmentId})
for it.Next() {
	c := it.Current()
	fmt.Println(c.Id, c.Email)
}
if err := it.Err(); err != nil {
	log.Fatal(err)
}

all, err := client.Webhooks.ListAll(ctx, nil).All() // everything at once, for a short list
  • Pagine da 100 elementi (o Limit), after seguito finché has_more è vero; una pagina viene richiesta solo quando serve. I filtri dell'opzione vengono mantenuti a ogni pagina; Before viene ignorato.
  • Un errore interrompe lo scorrimento: Next restituisce false e Err lo riporta.
  • ListAll su Emails, Emails.Receiving, ApiKeys, Domains, Suppressions, Contacts, Contacts.Imports, Segments, Broadcasts, Forms, NewsletterTemplates, Automations, Webhooks, Webhooks.Deliveries; e inoltre Emails.EventsAll, Segments.ListContactsAll, Broadcasts.RecipientsAll, Forms.SignupsAll, Automations.RunsAll.

Il resto

Go
client.Batch.SendWithOptions(ctx, reqs, &voaaro.BatchSendEmailOptions{BatchValidation: voaaro.BatchValidationPermissive})
client.Emails.Get(id)
client.Emails.List()
client.Emails.Update(&voaaro.UpdateEmailRequest{Id: id, ScheduledAt: "in 2 hours"})
client.Emails.Cancel(id)
client.Emails.Events(&voaaro.ListEmailEventsOptions{Type: "bounced", CreatedAfter: "2026-11-01T00:00:00Z"})
client.Emails.Receiving.List(&voaaro.ListReceivedOptions{ListOptions: voaaro.ListOptions{Limit: 10}})
client.Domains.Create(&voaaro.CreateDomainRequest{Name: "notify.example.com"})
client.Suppressions.Add(&voaaro.AddSuppressionRequest{Email: "former.customer@example.org", Domain: "example.com"})
client.ApiKeys.Create(&voaaro.CreateApiKeyRequest{Name: "CI", Permission: voaaro.PermissionSendingAccess})
client.Contacts.Create(&voaaro.CreateContactRequest{Email: "ada@example.org", FirstName: "Ada"})
client.Broadcasts.Create(&voaaro.CreateBroadcastRequest{SegmentId: segmentId, From: from, Subject: subject, Html: html, Send: true})

Servizi: Emails (con Attachments e Receiving), Batch, ApiKeys, Domains, Suppressions, Contacts (con Imports), Segments, Audiences, Topics, ContactProperties, Broadcasts, Newsletter, Forms, NewsletterTemplates, Automations, Events, Webhooks (con Deliveries), Organizations (chiave operatore mko_…).

Newsletter

Go
client.Newsletter.UpdateSettings(&voaaro.UpdateNewsletterSettingsRequest{
	From:          voaaro.String("Acme <news@example.com>"),
	PostalAddress: voaaro.String("Acme\n12 Lilac Street\nSpringfield"),
})
o, _ := client.Newsletter.Overview(&voaaro.NewsletterOverviewOptions{Days: 30})

f, _ := client.Forms.Create(&voaaro.CreateFormRequest{Name: "Website newsletter", SegmentIds: []string{segmentId}})
filter := &voaaro.SegmentFilter{Match: "all", Conditions: []voaaro.SegmentCondition{{"field": "opened", "op": "none", "days": 90}}}
preview, _ := client.Segments.Preview(&voaaro.PreviewSegmentRequest{Filter: filter})

client.Broadcasts.Links(broadcastId)
client.Broadcasts.ChooseWinner(broadcastId, "b")
csv, _ := client.Broadcasts.Export(broadcastId) // []byte

tpl, _ := client.NewsletterTemplates.Create(&voaaro.CreateNewsletterTemplateRequest{Name: "Monthly letter", Subject: "What's new", Html: html})
client.Events.Send(&voaaro.SendEventRequest{Email: "ada@example.org", Name: "purchase", Data: map[string]any{"total": 42}})
client.Contacts.Cleanup(&voaaro.CleanupContactsRequest{Days: 180}) // simulation; DryRun: voaaro.Bool(false) to act

Automations.Create accetta un AutomationTrigger e dei valori AutomationStep; il campo Domain indica il dominio quando la chiave ne copre più di uno. Dettaglio delle route: Newsletter.

Iscrizione e disiscrizione dalla tua applicazione (server: Newsletter.Subscribe, Unsubscribe, GetSubscription; browser: NewPublicForm, SolveChallenge), programmazione delle campagne (Broadcasts.Schedule, Unschedule, SendNow, ListScheduled, Check): consulta le guide Il tuo modulo di iscrizione, Disiscrizione dalla tua applicazione e Programmare una campagna, con esempi per ogni SDK.

Qualità dei contatti e recapito: verifica di un indirizzo senza salvarlo (Contacts.VerifyEmail) o di quello di un contatto (Contacts.Reverify), filtri di coinvolgimento e di stato dell'indirizzo (Engagement, EmailStatus), esportazione CSV (Contacts.Export), importazione senza gli indirizzi non validi (SkipInvalid) e punteggio di recapito di una campagna (Broadcasts.Deliverability): vedi Contatti, segmenti e argomenti e Campagne, con esempi per ogni SDK.

Webhook

Go
event, err := voaaro.VerifyWebhookRequest(r, os.Getenv("VOAARO_WEBHOOK_SECRET"))

Legge il corpo (al massimo 5 MB) e lo ripristina, verifica la firma e l'età (5 minuti); in caso di errore, errors.Is(err, voaaro.ErrWebhookVerification) è vero.

Più segreti: voaaro.VerifyWebhookRequestWithSecrets(r, nuovoSegreto, vecchioSegreto), voaaro.VerifyWebhookWithSecrets(corpo, firma, nuovoSegreto, vecchioSegreto), oppure il campo WebhookSecrets di VerifyWebhookOptions per client.Webhooks.Verify. La notifica viene accettata se uno dei segreti corrisponde a uno dei v1 dell'intestazione. Esempio completo e rotazione: Firma.

Gestire gli endpoint (dettagli):

Go
hook, _ := client.Webhooks.Create(&voaaro.CreateWebhookRequest{
	Endpoint: "https://app.example.com/webhooks/voaaro",
	Events:   []string{"email.bounced"},
})
secret := hook.SigningSecret // shown only once
client.Webhooks.RotateSecret(hook.Id, &voaaro.RotateWebhookSecretRequest{GraceHours: voaaro.Int(24)})

it := client.Webhooks.Deliveries.ListAll(ctx, hook.Id, &voaaro.ListWebhookDeliveriesOptions{Status: "failed"})
for it.Next() {
	client.Webhooks.Deliveries.Replay(hook.Id, it.Current().Id)
}
Esc