Jump to

  • Quickstarts
  • API reference
  • Webhook events
  • Error codes
  • SDKs

Resources

Go SDK

Call the Trovacast API from Go 1.24 or later with a standard-library client: typed methods and models, a context on every call, iterators, retries and webhook verification.

The Go SDK is the typed client for the Trovacast API on Go 1.24 or later, and it uses only the standard library. It is generated from the same OpenAPI contract as the API reference, and it follows the same retry, idempotency and error rules as the Node.js and Python SDKs.

Install

Use a copy of the module (bash)
go mod edit -replace github.com/trovakap/recalling-new/packages/trovacast-go=../trovacast-go

Here ../trovacast-go is the folder you put the copy in. Then import the package as trovacast:

Import the package (go)
import trovacast "github.com/trovakap/recalling-new/packages/trovacast-go"

Once the module is published, go get github.com/trovakap/recalling-new/packages/trovacast-go@latest fetches it. The changelog lists what changed in each version.

Create a client

Create a client (go)
package main

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

	trovacast "github.com/trovakap/recalling-new/packages/trovacast-go"
)

func main() {
	ctx := context.Background()
	client, err := trovacast.NewClient(os.Getenv("TROVACAST_API_KEY"))
	if err != nil {
		log.Fatal(err)
	}

	me, err := client.GetMe(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(me.Kind, me.Scopes)
}

NewClient returns an error when the key does not look like a Trovacast key (tc_…) or an option is invalid, and the error never repeats the key. A Client is safe for concurrent use, so make one and share it; printing or logging it shows only its base URL. The samples below continue inside main, with ctx and client in scope.

OptionDefaultWhat it does
WithBaseURL(url)https://api.trovacast.comThe API origin. A trailing /v1 is accepted. It must be https://, or http:// to a loopback host (localhost, 127.0.0.0/8 or [::1]); any other http:// URL fails with ErrInsecureBaseURL.
WithTimeout(d)30sThe timeout of each attempt: connecting, sending and reading the whole response.
WithMaxRetries(n)2Retries after the first attempt, for a failure that is safe to retry. From 0 to 10.
WithRetryDelay(initial, max)500ms, 8sThe first backoff step, which doubles on each retry with jitter, and the largest step.
WithMaxRetryAfter(d)60sThe longest Retry-After the client waits out. A longer one is returned at once with RetryAfter set, so your job queue can reschedule.
WithMaxResponseBytes(n)10 MiBThe longest response body the client reads. An error response's body is capped at 1 MiB, or at n when that is smaller.
WithUserAgent(ua)Not setYour own product token, such as my-app/1.0, put before trovacast-sdk-go/<version> in the User-Agent.
WithHTTPClient(c)http.DefaultClientYour *http.Client, for proxies or transports. The SDK sends with a copy that never follows a redirect, and leaves yours unchanged.
WithOrganization(id)Not setFor an integration key: the organization every call acts for, sent as Trovacast-Organization. The key needs organizations:act.

Per call, pass WithIdempotencyKey, WithoutIdempotencyKey, WithRequestTimeout, WithResponseInfo or ForOrganization after the other arguments. ForOrganization("") sends no organization, for your integration's own routes such as CreateOrganization.

Make a request

Methods are the operationIds in Go case: CreateMessage, GetWhatsAppConsent, ListSMSSenders. Each takes a context.Context, the path parameters in order, a pointer to its query parameters (*<Method>Params) when it has any, a pointer to its body when it takes one, and request options. It returns a pointer to the decoded answer, or only an error for a 204. Operations() lists every operation with its method name.

Send a WhatsApp template (go)
contact, err := client.UpsertContact(ctx, &trovacast.UpsertContact{
	Phone:       "+919876543210",
	DisplayName: trovacast.Ptr("Aarav"),
}, trovacast.WithIdempotencyKey("order-1001-contact"))
if err != nil {
	log.Fatal(err)
}

message, err := client.CreateMessage(ctx, &trovacast.CreateMessage{
	Type:      trovacast.CreateMessageTypeTemplate,
	ContactID: trovacast.Ptr(contact.ID),
	Template:  &trovacast.MessageTemplateSelector{Name: trovacast.Ptr("order_confirmation"), Language: trovacast.Ptr("en")},
	Variables: map[string]string{"var1": "Aarav", "var2": "#1001"},
}, trovacast.WithIdempotencyKey("order-1001-confirmation"))
if err != nil {
	log.Fatal(err)
}
fmt.Println(message.ID, message.Status) // queued; later statuses arrive by webhook

WithIdempotencyKey names the write's key. A key built from your order id makes the send safe to repeat: a retried job gets the first answer back instead of sending twice. The WhatsApp template quickstart walks through the whole send.

Optional and nullable fields

Every schema is a Go type with the API's own JSON names, named without a leading Public or a trailing Dto (Contact, CreateMessage). A required field is a value and an optional one a pointer, which trovacast.Ptr makes. An optional field the API also accepts as null, which clears the value on an update, is a trovacast.Nullable: its zero value is left out, trovacast.Null[T]() sends null and trovacast.NewNullable(v) sends a value.

Clear a number's label (go)
number, err := client.GetNumber(ctx, "NUMBER_ID")
if err != nil {
	log.Fatal(err)
}
_, err = client.UpdateNumber(ctx, number.ID, &trovacast.UpdateNumber{
	Version: number.Version,
	Label:   trovacast.Null[string](), // clears the label
})
if err != nil {
	log.Fatal(err)
}

Query parameters go out under the API's names: a nil field is left out, and a time.Time is sent as ISO 8601 in UTC. Timestamps in bodies and answers are RFC 3339 strings, and trovacast.FormatTime(t) writes one.

Read the response details

WithResponseInfo(&info) fills a ResponseInfo with the HTTP side of a successful answer: Status, Header, RequestID, IdempotencyKey, IdempotentReplayed and RateLimit. Use it when the status matters, as when an upsert tells a new contact (201) from an existing one (200).

Tell a new contact from an existing one (go)
var info trovacast.ResponseInfo
contact, err := client.UpsertContact(ctx, &trovacast.UpsertContact{Phone: "+919876543210"}, trovacast.WithResponseInfo(&info))
if err != nil {
	log.Fatal(err)
}
fmt.Println(contact.ID, info.Status == http.StatusCreated, info.RequestID, info.RateLimit)

RateLimit holds Limit, Remaining and Reset from the X-RateLimit-* headers, or is nil when they are absent. RateLimitFromHeader and ParseRetryAfter are exported for your own use. See Rate limits.

Paginate

Every list operation has an iterator, <Method>Iter, that fetches the next page only when the walk needs it. Call Next(ctx) until it returns false, read each item with Item(), and check Err() at the end.

Every message of a contact (go)
it := client.ListMessagesIter(&trovacast.ListMessagesParams{ContactID: trovacast.Ptr("CONTACT_ID")})
for it.Next(ctx) {
	message := it.Item()
	fmt.Println(message.ID, message.Status)
}
if err := it.Err(); err != nil {
	log.Fatal(err)
}

All(ctx) ranges over the same items, with an error as the last pair:

The events of the last three days (go)
since := time.Now().Add(-72 * time.Hour)
for event, err := range client.ListEventsIter(&trovacast.ListEventsParams{CreatedAfter: &since}).All(ctx) {
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(event.ID, event.Type)
}

A Cursor in the params is where the walk starts, and it.Cursor() is the next page's cursor, to resume later. The walk stops when nextCursor is null, and fails if the API answers the same cursor twice or something that is not a page. See Pagination.

Handle errors

Every failed call returns an *APIError. Read it with errors.As and branch on its Code, which is stable; the Message is written for people.

Handle a missing contact (go)
contact, err := client.GetContact(ctx, "CONTACT_ID")
var apiErr *trovacast.APIError
switch {
case errors.As(err, &apiErr) && apiErr.IsNotFound():
	fmt.Println("no such contact", apiErr.RequestID)
case err != nil:
	log.Fatal(err)
default:
	fmt.Println(contact.ID)
}
FieldWhat it holds
StatusThe HTTP status, or 0 when no response arrived.
CodeThe API's code as an ErrorCode, such as ErrorCodeConsentRequired, or one the SDK sets when no answer arrived or it could not be read: ErrorCodeNetworkError, ErrorCodeTimeout, ErrorCodeInvalidResponse or ErrorCodeUnexpectedRedirect. A proxy's answer without a code is HTTP_<status>.
MessageReadable text. Validation messages are joined with ; .
RequestIDThe API's request id. Quote it to support.
DocURLThe code's entry in the error reference, or empty.
RetryableWhether repeating the call later is safe and could succeed. The client has already spent its own retries when you see it.
RetryAfterThe server's Retry-After as a time.Duration, or 0.
IdempotencyKeyThe key the write was sent with. Reuse it when you retry.
IdempotentReplayedtrue when the API answered from its idempotency store: the outcome for that key is fixed.
BodyThe parsed error body as a map[string]any, with any extra fields the API sent.
IsNotFound()true for a 404.

Error() reads trovacast: <code> (HTTP <status>): <message>. KnownErrorCodes() lists every code this release knows, and IsKnownErrorCode(code) tells a known code from a newer one: read a code you do not know by its Status. The error never holds the API key, a request body or a URL, so it is safe to log.

  • A cancelled context comes back as ctx.Err() itself, at once, even between retries.
  • A call that cannot be sent, such as one with an empty path value or a missing required query parameter, returns a plain error before anything goes out.
  • A response longer than the size limit is closed unread, and the call returns an *APIError whose cause is a *ResponseTooLargeError with Status and Limit.

Retries and idempotency

Every write (POST, PUT, PATCH or DELETE) carries an Idempotency-Key. By default the client mints a fresh UUID for each call and sends the same key on every retry of that call, so a retry whose first attempt landed gets the stored answer instead of running twice. WithIdempotencyKey(key) sends your own, 1 to 255 visible ASCII characters, to make a write safe across processes and restarts too. An empty key is refused, since a fresh key in its place would let a re-run job send twice. WithoutIdempotencyKey() sends none, and that write is then never retried.

  • Retried: a timeout, a network error, 429, 500, 502, 503, 504 and 409 IDEMPOTENCY_KEY_IN_FLIGHT, up to WithMaxRetries times, with exponential backoff and jitter (500 ms, doubling, at most 8 s) and never sooner than Retry-After. Only reads, and writes that carry a key, are retried.
  • Returned at once: a Retry-After longer than WithMaxRetryAfter, with RetryAfter set for your job queue, and any error the API replayed from its idempotency store.
  • Replayed errors: when IdempotentReplayed is true, every retry with that key gets the same answer. Read the resource to see whether the first attempt took effect, and only if it did not, send the write again with a new key.
  • Unreadable successes: a 2xx whose body does not decode is INVALID_RESPONSE and is never retried. The write may have landed, so retry it with the error's IdempotencyKey.
  • A redirect is never followed, so the key never travels to another URL.

Idempotency explains what the API stores against a key, and for how long.

Verify webhooks

Verify the raw body before you parse it. VerifyWebhook(payload, header, secret, tolerance) checks the Trovacast-Signature header in constant time and returns the parsed event; a tolerance of 0 means the default 300 seconds. A delivery that fails returns a *WebhookError, whose Reason says why; answer it with 400. Any other error is a misconfiguration, such as an empty secret.

Verify a delivery with net/http (go)
package main

import (
	"errors"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"

	trovacast "github.com/trovakap/recalling-new/packages/trovacast-go"
)

func main() {
	secret := os.Getenv("TROVACAST_WEBHOOK_SECRET")
	http.HandleFunc("/trovacast/webhook", func(w http.ResponseWriter, r *http.Request) {
		payload, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20)) // the exact bytes
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		event, err := trovacast.VerifyWebhook(payload, r.Header.Get(trovacast.WebhookSignatureHeader), secret, 0)
		var refused *trovacast.WebhookError
		if errors.As(err, &refused) {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		if err != nil {
			log.Print(err) // a misconfiguration, such as an empty secret
			w.WriteHeader(http.StatusInternalServerError)
			return
		}
		// Deliveries arrive at least once: deduplicate on event.ID.
		if event.Type == trovacast.WebhookEventTypeMessageDelivered {
			var data trovacast.WebhookEventMessageDeliveredData
			if err := event.DecodeData(&data); err == nil {
				fmt.Println(data.Message.ID)
			}
		}
		w.WriteHeader(http.StatusNoContent)
	})
	log.Fatal(http.ListenAndServe(":3000", nil))
}

Each event type's data is a generated struct, such as WebhookEventMessageDeliveredData, and event.DecodeData reads it. ParseWebhookEvent parses a body you have already verified, and in your own tests CreateWebhookSignatureHeader(payload, secret, time.Now()) signs a delivery. The scheme itself is described under Webhooks.

Rotate a secret

After you rotate an endpoint's secret, every delivery for the next 24 hours carries a second v1 signature made with the previous secret. A WebhookVerifier accepts a delivery signed with any of its secrets, so give it both while you deploy the new one:

Accept the new and the previous secret (go)
verifier := trovacast.WebhookVerifier{
	Secrets: trovacast.WebhookSecretsOf(os.Getenv("TROVACAST_WEBHOOK_SECRET"), os.Getenv("TROVACAST_WEBHOOK_SECRET_PREVIOUS")),
}
event, err := verifier.Verify(payload, r.Header.Get(trovacast.WebhookSignatureHeader))

Tolerance sets the window (0 is the default 300 seconds) and Now the clock, for tests. VerifySignature checks the signature alone. For a repeated header, pass its values joined with commas. Neither the verifier nor its Secrets ever prints a secret, under any fmt verb or in log/slog.

Build call flows

The call-flow builders are in the Node.js and Python SDKs. In Go, build a call flow from the generated CallFlowDocument types, pass it as a flow's Definition, and check a document without storing it with ValidateCallFlow.

Next steps