Installazione
go get github.com/deveryidea/voaaro-go@latestVersione 0.4.0. Go 1.21 o successivo, nessuna dipendenza (libreria standard). Pacchetto voaaro.
Configurazione
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 drawnOpzioni: WithBaseURL, WithMaxRetries, WithHTTPClient, WithUserAgent, WithHeader. Timeout predefinito: 60 secondi. Indica sempre l'indirizzo della tua istanza con WithBaseURL (o VOAARO_BASE_URL).
Invio
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_exceededo un 500, 502, 503, 504: 2 tentativi per impostazione predefinita (WithMaxRetries(n)). Mai dopodaily_quota_exceededné dopo un altro errore4xx. Attesa:Retry-After(al massimo 60 secondi), altrimenti 0,5 s × 2^n con una componente casuale, al massimo 8 secondi; l'annullamento delcontextinterrompe l'attesa. - Ogni richiesta di creazione ha un campo
IdempotencyKey(CreateContactRequest,CreateWebhookRequest,AddSuppressionRequest,CreateFormRequest…); per qualsiasi altroPOST, usavoaaro.WithIdempotencyKey(ctx, chiave)con la varianteWithContext. - 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.
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):
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),afterseguito finchéhas_moreè vero; una pagina viene richiesta solo quando serve. I filtri dell'opzione vengono mantenuti a ogni pagina;Beforeviene ignorato. - Un errore interrompe lo scorrimento:
NextrestituiscefalseeErrlo riporta. ListAllsuEmails,Emails.Receiving,ApiKeys,Domains,Suppressions,Contacts,Contacts.Imports,Segments,Broadcasts,Forms,NewsletterTemplates,Automations,Webhooks,Webhooks.Deliveries; e inoltreEmails.EventsAll,Segments.ListContactsAll,Broadcasts.RecipientsAll,Forms.SignupsAll,Automations.RunsAll.
Il resto
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
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 actAutomations.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
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):
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)
}