GoMenu
On this page

Go

Integrate with the Kirora API using the Go library: typed requests, iterators for pagination, retries and webhook verification.

View as MarkdownOpen in ClaudeOpen in ChatGPTUpdated

Use kirora-go to call the Kirora /v1 API from a Go server with typed requests, pagination, retry handling and webhook verification. It works like the Node.js library, with Go’s own conventions. This page covers the common tasks; the README is the full reference, and pkg.go.dev documents every type.

Install

Add the module with go get:

Terminal
go get github.com/kiroratech/kirora-go

It needs Go 1.24 or later and has no dependencies outside the standard library. Import it as kirora:

Go
import kirora "github.com/kiroratech/kirora-go"

Create a client

Keep your API key on your server and set it as KIRORA_API_KEY. NewClient("") reads it from there:

Go
client, err := kirora.NewClient("") // reads KIRORA_API_KEY
if err != nil {
	log.Fatal(err)
}

Create one client and reuse it; it’s safe for concurrent use. NewClient takes the API key, or "", and options:

Option Default Description
WithBaseURL(url) KIRORA_BASE_URL, or https://api.kirora.io For tests and mocks. The host only, without a version: the client adds /v1 to each path.
WithTimeout(d) 30s How long each attempt may take, including reading the response.
WithMaxRetries(n) 3 Attempts after the first, from 0 to 10. 0 disables retrying.
WithMaxRetryDelay(d) 30s Ceiling for a single wait between attempts.
WithHTTPClient(c) http.DefaultClient A custom *http.Client, such as one with a proxy.
WithWorkspace(externalID) None Partner keys only: the tenant workspace’s externalId. See Partner workspaces.
WithHeader(name, value) None An extra header on every request.
WithAppInfo(name, version) None Your app’s name and optional version, added to the User-Agent.

Each resource is a service on the client, and each method is named after its operationId with the resource dropped, so identifyContact is client.Contacts.Identify() and sendCampaign is client.Campaigns.Send(). Methods return the response’s data, already unwrapped.

Service Methods
Contacts List, All, Get, Update, Delete, Identify, IdentifyBatch, DeleteBatch, Merge, Export, ListLists, AllLists, ListTopics, SetTopic, ListInstallations, AllInstallations, RegisterInstallation, DeleteInstallation
Lists List, All, Get, Create, Update, Delete, AddContacts, DeleteContacts
Campaigns List, All, Get, Create, Send, Trigger, Schedule, Eligibility
Transactional Send, SendBatch, Cancel
Events Track, TrackBatch
Messages List, All, Get
Suppressions List, All, Add, Delete
Workspaces List, All, Create, Get, Update, Delete, Suspend, Resume, CancelDeletion (partner keys only)
EmbedSessions Create (partner keys only)

On the client itself, client.Me(ctx) returns the API key in use, its scopes and the workspace it acts in, and client.ForWorkspace(externalID) returns a copy that acts in one of your tenants.

Methods that take a contact name it by Kirora’s id, your externalId or its email: kirora.ContactID(id), kirora.ContactExternalID(userID) or kirora.ContactEmail("[email protected]").

For an operation without a method, call client.Request(ctx, method, path, body, &out), or kirora.RequestAll[T](ctx, client, path, params) for a list; both use the same auth, retries and error mapping. See Other endpoints.

Optional fields

Request types are generated from the API’s spec. Optional fields are pointers, so set them with kirora.Ptr:

Go
&kirora.ListContactsParams{Limit: kirora.Ptr(100), Suppressed: kirora.Ptr(false)}

A field that can also be set to null is a kirora.Nullable[T]. Leave it out to keep the current value, set it with kirora.Value(v), or clear it with kirora.Null[T]():

Go
client.Contacts.Update(ctx, kirora.ContactID(contactID), &kirora.UpdateContactInput{
	FirstName: kirora.Value("Olivia"),
	LastName:  kirora.Null[string](), // clears it
	// Phone is left as it is
})

Enums are string types with constants, such as kirora.CampaignScheduleTypeFixed. Each has an IsKnown() method, which is false for a value added to the API after your version of the library.

Identify a contact

Contacts.Identify() calls identifyContact: an upsert resolved by externalId, then email, then phone. It is safe to repeat; it converges rather than creating duplicates.

Go
contact, err := client.Contacts.Identify(ctx, &kirora.IdentifyContactInput{
	ExternalID: kirora.Value("cust_1042"),
	Email:      kirora.Value("[email protected]"),
	FirstName:  kirora.Value("Olivia"),
})
if err != nil {
	return err
}
fmt.Println(contact.ID)

Track an event

Events.Track() calls trackEvent. The idempotency key is optional; pass one derived from your own event or order id to make your own retries safe too. Without one, the library makes one per call, which covers only its own retries.

Go
event, err := client.Events.Track(ctx, &kirora.TrackEventInput{
	ExternalID: kirora.Ptr("cust_1042"),
	Name:       "Order Completed",
	Properties: map[string]any{"order_id": "1042", "total": 42.5, "currency": "USD"},
}, kirora.WithIdempotencyKey("order-1042-completed"))

Events.TrackBatch() sends up to 100 events at once. One event refused doesn’t stop the rest: the call succeeds, and each entry in Results, in the order you sent them, has either the Event or an Error:

Go
result, err := client.Events.TrackBatch(ctx, &kirora.TrackEventsBatchInput{Events: entries})
if err != nil {
	return err // the whole batch was refused
}
for i, entry := range result.Results {
	if entry.Error != nil {
		log.Printf("event %d not tracked: %s", i, entry.Error.Code)
	}
}

Send a transactional message

Transactional.Send() calls sendTransactionalMessage. The key is optional, but pass your own, made once per logical send before the first attempt and outside any retry loop: a retry with the same key and body then replays the first send for as long as its message is kept (Retention). Without one, the library makes one per call, which covers only its own retries. See Idempotency.

Go
orderID := "1042"

sent, err := client.Transactional.Send(ctx, &kirora.SendTransactionalInput{
	To:    kirora.ContactIdentifier{Email: kirora.Ptr("[email protected]")},
	Data:  map[string]any{"order_id": orderID},
	Email: &kirora.SendTransactionalInputEmail{Template: kirora.Ptr("order-receipt")}, // its alias or its id
}, kirora.WithIdempotencyKey("receipt-"+orderID))

Transactional.SendBatch() calls sendTransactionalMessagesBatch: up to 100 messages, each with its own IdempotencyKey, and results per entry as with Events.TrackBatch(). Transactional.Cancel(ctx, messageID) cancels a message scheduled with SendAt.

Paginate

All() (and AllLists(), AllInstallations()) iterates over every item with range, fetching pages as you go. break whenever you’ve had enough; no further pages are fetched:

Go
for contact, err := range client.Contacts.All(ctx, &kirora.ListContactsParams{Limit: kirora.Ptr(100)}) {
	if err != nil {
		return err
	}
	fmt.Println(contact.Email)
}

List() fetches one page. To fetch the next page yourself, pass its NextCursor back as Cursor, with the same filters. It’s nil on the last page. Treat the cursor as opaque.

Go
params := &kirora.ListContactsParams{Limit: kirora.Ptr(100)}
page, err := client.Contacts.List(ctx, params)
if err != nil {
	return err
}

if cursor := page.Meta.Pagination.NextCursor; cursor != nil {
	params.Cursor = cursor
	next, err := client.Contacts.List(ctx, params)
}

Cancelling the context stops iteration before the next item, even one from a page already fetched. See Pagination.

Errors

Every error the API returns is a *kirora.Error. Branch on Code, never on the message:

Go
_, err := client.Campaigns.Send(ctx, campaignID)
if kirora.IsErrorCode(err, kirora.ErrorCodeSendingDomainUnverified) {
	// Recoverable: publish the DNS records and check the domain.
}
var apiErr *kirora.Error
if errors.As(err, &apiErr) {
	log.Printf("Kirora request failed: %s (request %s)", apiErr.Code, apiErr.RequestID)
}
Field Description
Code The API’s error code, with a constant for each published one, such as kirora.ErrorCodeNotFound. A code added after your version still comes through; Code.IsKnown() tells you which.
Message Human-readable; for logs, not for branching.
StatusCode The HTTP status.
Errors On VALIDATION_ERROR and DRAFT_INCOMPLETE, each field the request got wrong, with a message to show beside it.
Details What else the code reports, as raw JSON. Its shape depends on the code; see Errors.
RequestID The X-Request-Id response header, for support.
RetryAfter The Retry-After header, when the server sent one.
RateLimit The rate limit headers, when the server sent them.

Other failures return other errors:

  • *kirora.ConnectionError: no complete response, such as a network error, or the connection dropping while the body was read. Timeout() is true when an attempt took longer than its timeout.
  • *kirora.ResponseError: a success status with a body the library can’t use, such as HTML from a proxy.
  • The context’s error, such as context.Canceled, when you cancel a call.

Retries and timeouts

Every request goes through one retry loop, which repeats a call only when repeating it is safe. Whether an operation is safe to repeat comes from the API’s spec, not from each method:

  • 429 is always retried, as are connections never made, such as a failed DNS lookup: the server did nothing.
  • 5xx and other network failures are retried only when a repeat can’t cause a duplicate: reads, operations that converge on the same result, and writes with an idempotency key, which the library makes per call wherever the endpoint takes one and reuses on each retry.
  • IDEMPOTENCY_KEY_IN_USE (409) is retried when the call has a key: an earlier attempt, such as one that timed out, is still running, and waiting gets its response.
  • Other 4xx errors are never retried, including the other idempotency 409s, IDEMPOTENCY_KEY_REUSED and IDEMPOTENCY_KEY_OUTCOME_UNKNOWN.
  • Backoff: exponential with jitter, capped at WithMaxRetryDelay. When the server sends Retry-After, the retry never comes sooner.
  • Bounded: at most WithMaxRetries retries (default 3), then the last error is returned. A retry sends the same body and idempotency key as the first attempt.
  • Timeout: WithTimeout (default 30s) applies to each attempt, so a call that retries can take longer in total. For an overall deadline, use the context. A cancelled call is never retried.

Per-call options

Every method takes a context.Context first and options last. The client’s options also apply to a single call, overriding the client’s, and two apply only to a call:

Option Description
WithIdempotencyKey(key) On methods that create, send or record something.
WithResponseInto(&resp) Stores the HTTP response’s details in a kirora.Response.
WithWorkspace(externalID) Partner keys only: the tenant to act in for this call.
WithTimeout(d), WithMaxRetries(n) Override the client’s settings for this call.

Passing an option to the wrong place doesn’t compile. kirora.Response holds the response’s RequestID, its RateLimit, and IdempotencyReplay, which is true when an earlier request with the same key already did the work and this is its stored response:

Go
var resp kirora.Response
contact, err := client.Contacts.Get(ctx, kirora.ContactID(contactID), kirora.WithResponseInto(&resp))
fmt.Println(resp.RequestID) // quote this to Kirora support

Verify webhooks

Verify each webhook against the raw request body, before parsing it: parsed and re-serialized JSON won’t match the signature. VerifyWebhook(secret, r, opts) reads the body and the X-Webhook-* headers, checks the signature in constant time, rejects a timestamp more than 5 minutes from now, and accepts any of the signatures sent while a secret rotation overlaps:

Go
http.HandleFunc("/webhooks/kirora", func(w http.ResponseWriter, r *http.Request) {
	headers, body, err := kirora.VerifyWebhook(os.Getenv("KIRORA_WEBHOOK_SECRET"), r, nil)
	var verr *kirora.WebhookVerificationError
	if errors.As(err, &verr) {
		log.Printf("rejected a webhook: %s", verr.Reason)
		http.Error(w, "invalid webhook", http.StatusUnauthorized)
		return
	} else if err != nil {
		http.Error(w, "", http.StatusInternalServerError)
		return
	}

	// Delivery is at-least-once: deduplicate on headers.EventID, then parse body.
	log.Println(headers.Event, headers.EventID, len(body))
	w.WriteHeader(http.StatusOK)
})

verr.Reason says why one was rejected: invalid_timestamp, invalid_headers, signature_mismatch (usually the wrong secret, or a body that was read and changed first), timestamp_outside_tolerance (a replay, or your server’s clock is out of sync) or body_too_large (over 10 MiB). Pass &kirora.WebhookOptions{Tolerance: kirora.Ptr(d)} to change the replay window.

If your framework has already read the body, use ReadWebhookHeaders() and VerifyWebhookSignature() with the raw bytes instead, then take the event type and id from the verified body’s eventType and eventId: the signature doesn’t cover the headers. headers.Event is a kirora.WebhookEvent, with constants such as kirora.WebhookEventMessageDelivered; treat the type as open, because a * subscription receives types added later. See Webhooks.

Partner workspaces

With a partner key, act in one of your tenants’ workspaces by its externalId, with client.ForWorkspace(), or with WithWorkspace on the client or on a single call. Each is sent as the Kirora-Workspace header; a call’s option overrides the client’s. An empty externalId is refused rather than acting in your own workspace.

Go
tenant := client.ForWorkspace("tenant-42")
contact, err := tenant.Contacts.Get(ctx, kirora.ContactID(contactID))

Manage the workspaces themselves with client.Workspaces. Delete() takes effect after a grace period, which CancelDeletion() stops.

To embed Kirora’s segment or email builder in your app, create a session for the tenant on your server and give its token to the browser. A session lasts 15 minutes.

Go
session, err := client.ForWorkspace("tenant-42").EmbedSessions.Create(ctx, &kirora.CreateEmbedSessionInput{
	Components: []kirora.EmbedComponent{kirora.EmbedComponentEmailBuilder},
})

Sign tokens for the web SDK

The web SDK signs users in with a token from your server. CreateUserToken(secret, userID, lifetime) signs one:

Go
token, err := kirora.CreateUserToken(os.Getenv("KIRORA_SDK_TOKEN_SECRET"), user.ID, kirora.DefaultUserTokenLifetime)

secret is the workspace’s SDK token secret, from Developer → SDK in the dashboard; it never leaves your server. userID is your own id for the user, their contact’s externalId. kirora.DefaultUserTokenLifetime is an hour; pass another lifetime in whole seconds, up to Kirora’s limit of 24 hours. It needs no client and no API key. The web SDK’s setup has the whole route.

Other endpoints

For an operation without a method, client.Request() decodes the whole JSON body, envelope included, and kirora.RequestAll[T]() pages like the services’ All() methods:

Go
type Segment struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

var resp struct {
	Data Segment `json:"data"`
}
err := client.Request(ctx, http.MethodGet, "/v1/segments/"+url.PathEscape(segmentID), nil, &resp)

for segment, err := range kirora.RequestAll[Segment](ctx, client, "/v1/segments", nil) {
	// ...
}

For a large body, such as an export to stream to a file, client.RequestRaw() returns the *http.Response with its body unread; close it when done. An endpoint newer than your version of the library is retried as a write only if you pass WithIdempotencyKey.

Test your code

To test code that calls Kirora, point the client at an httptest.Server that answers with canned JSON, and turn retries off so a failure shows at once:

Go
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	if r.Method == http.MethodGet && r.URL.Path == "/v1/lists/beta" {
		fmt.Fprint(w, `{"data":{"id":"beta","name":"Beta testers"}}`)
		return
	}
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprint(w, `{"error":{"code":"NOT_FOUND","message":"no such route"}}`)
}))
defer server.Close()

client, err := kirora.NewClient("test-key", kirora.WithBaseURL(server.URL), kirora.WithMaxRetries(0))

The services are concrete types, not interfaces, so new methods never break your code. To mock at your own boundary instead, define a small interface with just the methods you call: a *kirora.ContactsService satisfies it.