*http.Request inside *gin.Context, so unwrap it: c.Request for verifier.ParseRequest. Body-binding or body-logging middleware must not read the webhook body first; Gin’s built-in request logger does not read it.
Prerequisites
- Go 1.25 or newer, which Gin 1.12 requires
- An AhaSend account with a verified sending domain
- An API key with the domain-scoped
messages:send:{yourdomain.com}permission, and your account ID
Install the SDK
google/uuid is a transitive dependency of the SDK, but the account ID is a uuid.UUID, so your own code imports it directly and it needs its own go get.
Configure Environment Variables
golang.org/x/time/rate limiter keyed by caller is enough — so one leaked credential or one looping client cannot drain the account.
Create the Client
Create the client once at startup and share it across handlers so its transport and rate limiter are reused. Automatic idempotency keys are still generated per request:main.go
SetTrustedProxies(nil) ignores client-supplied forwarding headers. If a load balancer or reverse proxy terminates HTTPS, replace nil with only that proxy’s IP addresses or CIDRs. SetMode(gin.ReleaseMode) matters for more than log volume: Gin defaults to debug mode, and in debug mode a recovered panic writes the request’s entire header block to the error log — cookies, webhook-signature, and everything else except Authorization.
Send an Email from a Gin Handler
send.go
202 carries one Data entry per recipient, and an entry can report Status == "error" with a nil ID even though the SDK call itself returned no error. This handler sends to one recipient and checks the single entry it expects; loop over every entry once you extend Recipients. Split the failures the same way the handler does: a rejected payload, a revoked key, or a missing scope fails identically on every attempt, so surface it as a 500 and page someone, while a rate limit or an upstream 5xx is worth retrying — the rate-limit branch passes AhaSend’s own Retry-After back to the caller.
The SDK automatically retries transient failures and attaches an automatic idempotency key to each send. This handler overrides it with a stable key derived from the immutable signup ID so a later retry of the same business operation can reuse the key. Reuse a key only with the exact same payload: the API rejects the same key carrying a changed body with 422, which the SDK reports as ErrorTypeIdempotency and the handler turns into a 409 rather than a retryable 502. A 409 from the API is the separate in-progress case — an earlier request with that key has not finished — which the SDK reports as ErrorTypeIdempotencyConflict with the remaining seconds in RetryAfter. Stored outcomes replay for 24 hours, but a 5xx is not stored, so a retry after a server error can still send twice; persist workflow state and make uncertain results safe to reconcile.
Handle Webhooks
Gin handlers wrap a standard*http.Request, so the SDK’s ParseRequest works directly: it verifies the HMAC signature and timestamp, then returns a typed event. Timestamp validation is not replay deduplication. No body-parsing middleware may run on this route first.
webhook.go
https://your-app.com/webhooks/ahasend, and copy its secret into AHASEND_WEBHOOK_SECRET exactly as shown (including the aha-whsec- prefix).
This minimal receiver deliberately verifies and acknowledges without performing a business side effect. Before adding one, atomically commit the verified webhook-id header together with durable queue/outbox work; acknowledge an already-committed ID with 2xx, and process durable work idempotently. Do not launch a bare goroutine: it can be lost when the process exits, and *gin.Context is recycled once the handler returns, so anything that outlives the request must carry c.Copy() instead of c. Keep reverse-proxy request-size and concurrency limits at least as strict as the application limit above, return promptly, and keep failures opaque.
Going Further
- Templating: set
Substitutions: map[string]interface{}{"first_name": "Jane"}and use{{ first_name }}in the subject or body. - Batch sends:
Recipientsaccepts up to 100 entries; each gets a separate message. - Tags: set
Tags: []string{"welcome"}to filter messages in list and statistics queries. Webhooks are scoped by domain, not by tag, and message events do not carry the tags. - Rate limits: when sending at volume, tune
SetSendMessageRateLimit(requestsPerSecond, burstCapacity)to stay within your account’s limits. - Other frameworks: the same SDK patterns work in chi, Echo, and Fiber.
- Attachments: add
AttachmentswithData,ContentType,ContentDisposition: "attachment", andFileName. SetBase64: truefor binary files such as PDFs.
DomainsAPI, SuppressionsAPI, StatisticsAPI, and more).
Troubleshooting
401 from the API
401 from the API
The API key is missing, malformed, or revoked. Verify
AHASEND_API_KEY is set in the process environment and that the key exists in your dashboard.Webhook verification always fails
Webhook verification always fails
Something consumed the request body before
ParseRequest ran. Check for logging or body-buffering middleware on the webhook route. Also confirm the secret matches the dashboard exactly, including the aha-whsec- prefix.400 error mentioning the from address
400 error mentioning the from address
The
From address must belong to a verified sending domain on your account. Check domain status in the dashboard.
