Skip to content

Guide · Go

Async PDF rendering with a verified webhook in Go

A long report should not hold an HTTP request open. In async mode the API answers at once with a queued render and calls your endpoint when the PDF is ready. This guide has both halves in Go: the request, and a receiver that accepts only deliveries Formfeed really signed.

Free plan with 100 units a month, no credit card

Report with a chart
What comes out: Report with a chart

What you need

  • An API key. Create one in the app under API keys and export it as FORMFEED_API_KEY. A test key (ff_test_…) is right for trying things out. See the quick start.
  • Go. You need Go 1.26 or newer and the module github.com/formfeed-dev/formfeed-go, which needs nothing but the standard library.
  • The template. revenue-report from the report example, and its data.json next to the program.
  • A secret. 16 to 200 random characters in FORMFEED_WEBHOOK_SECRET, known to both programs. It signs the deliveries of this render, retries included.
  • A public URL. Replace https://example.com/hooks/formfeed with your endpoint. While developing, formfeed listen forwards deliveries to localhost without a tunnel.
InstallShell
go mod init render
go get github.com/formfeed-dev/formfeed-go

The program

The request names the template, switches to mode: "async" and says where to report. The answer comes back immediately with the status queued.

main.goGo
package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"

	formfeed "github.com/formfeed-dev/formfeed-go"
)

func main() {
	ctx := context.Background()
	client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))

	contents, err := os.ReadFile("data.json")
	if err != nil {
		log.Fatal(err)
	}
	var data map[string]any
	if err := json.Unmarshal(contents, &data); err != nil {
		log.Fatal(err)
	}

	// a problem answer (4xx, 5xx) is a *formfeed.Error with the API's code and detail
	render, err := client.Renders.Create(ctx, formfeed.RenderRequest{
		Template:      "revenue-report",
		Data:          data,
		Mode:          "async",
		WebhookURL:    "https://example.com/hooks/formfeed",
		WebhookSecret: os.Getenv("FORMFEED_WEBHOOK_SECRET"),
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(render.ID, render.Status) // queued: the webhook reports the rest
}

Run it

It prints the render’s id and queued. A few seconds later your endpoint receives render.completed with the full render, its download_url included, or render.failed with the reason.

Shell
export FORMFEED_API_KEY=ff_test_...
export FORMFEED_WEBHOOK_SECRET=$(openssl rand -hex 24)
go run main.go

What is particular about Go

  • Structs in, structs out. The request is a struct with the fields the API documents (formfeed.RenderRequest, formfeed.ProtectRequest), nested options such as Settings or Post are map[string]any; the answer is a struct as well: render.DownloadURL, render.PageCount and render.Units are fields, and render.Raw holds the whole answer.
  • Retries are built in. The client sends an Idempotency-Key with every render and retries 429, 503 and network errors up to three times with backoff, with the same key: a retry of a request that was answered already gets that answer back instead of a second render.
  • A context first, an error last. Every call takes a context.Context, and a cancelled one ends the call at once, a wait between retries included. A problem answer comes back as a *formfeed.Error: errors.As gives its Code (template_not_found, quota_exceeded, …), its Status and the RequestID support asks for.
  • Timeouts. The SDK’s own HTTP client waits at most 120 seconds for an answer, more than the 60 seconds after which a synchronous render answers 202 and goes on in the background. formfeed.WithHTTPClient sends over yours instead, with its own transport and limits.

The receiver

It listens on port 8080, reads the raw body, checks the signature and the age of the timestamp, and only then looks at the JSON. A delivery that fails the check gets 401.

hook.goGo
package main

import (
	"log"
	"net/http"
	"os"

	formfeed "github.com/formfeed-dev/formfeed-go"
)

func main() {
	hook := formfeed.Webhook{Secret: os.Getenv("FORMFEED_WEBHOOK_SECRET")}

	// Handler reads the raw body, checks its Webhook-Signature (the HMAC and the five-minute
	// tolerance) and answers 401 when either fails: only a delivery that passed reaches the function
	http.Handle("POST /hooks/formfeed", hook.Handler(func(w http.ResponseWriter, r *http.Request, event *formfeed.WebhookEvent) {
		switch event.Type {
		case "render.completed", "render.failed":
			render, err := event.Render()
			if err != nil {
				http.Error(w, err.Error(), http.StatusBadRequest)
				return
			}
			log.Println(event.Type, render.ID, render.DownloadURL)
		}
		w.WriteHeader(http.StatusNoContent)
	}))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Start the receiver

Shell
FORMFEED_WEBHOOK_SECRET=… go run hook.go

Verifying in Go

  • One handler verifies. Webhook.Handler reads the raw body, checks the HMAC with hmac.Equal and the five-minute tolerance, and answers 401 when either fails, so your function sees only deliveries that passed.
  • Another router. Handler is an http.Handler, which every router built on net/http mounts. Elsewhere, read the body once and hand the bytes to formfeed.ParseWebhook(secret, header, body), which answers formfeed.ErrInvalidSignature for a delivery that does not match.

What arrives

A POST with Webhook-Signature: t=<unix seconds>,v1=<hex>, where the hex is HMAC-SHA256 over t, a dot and the raw body, keyed with your secret exactly as you have it, as UTF-8 bytes: the webhook_secret you sent, or a registered endpoint’s whole whsec_… string, prefix included. Every attempt is signed anew with its own t. Webhook-Id stays the same across retries, so it is your deduplication key. data is the render as GET /renders/{id} returns it:

POST /hooks/formfeedJSON
{
  "id": "evt_5b0c8e6f2d4a4c3e9b1a7f6e5d4c3b2a",
  "type": "render.completed",
  "created_at": "2026-09-18T10:42:00Z",
  "workspace_id": "3a6f…",
  "data": {
    "id": "rnd_7da09ab6cd9946b798c187c2a9350852",
    "status": "succeeded",
    "download_url": "https://cdn.formfeed.dev/o/eu/…/document.pdf?exp=…&sig=…",
    "page_count": 2,
    "units": 1,
    …
  }
}

Retries, and what your endpoint owes

  • Answer fast. A delivery succeeds with a 2xx within 10 seconds. Store the event and do the work afterwards.
  • Retries. Anything else, a redirect included, is retried after 1 minute, 5 minutes, 30 minutes, 2 hours and 12 hours: six attempts in all, over about 14 hours and 40 minutes. The same event can therefore arrive twice: deduplicate by Webhook-Id.
  • Without a secret. A webhook_url without webhook_secret is delivered unsigned. For signed deliveries of every render, register an endpoint once in the app or through POST /webhooks; it gets its own secret.
  • Try it locally. formfeed listen --forward-to http://localhost:8080/hooks/formfeed relays the events of your test renders to your machine, signed with the session’s own secret rather than webhook_secret: start the receiver with that one, which formfeed listen --print-secret prints (run it before the session, since it ends a running one). formfeed trigger render.completed --template revenue-report makes a real test render whose event you watch arrive. The key needs the webhook:listen scope. See developing webhooks locally.

When the API says no

  • One shape for every error. Errors are problem documents (RFC 9457) with type, title, status, detail, a stable code and the request_id to quote to support; the type URL leads to a page about that error. The list is in the error reference.
  • The usual ones. 401 unauthorized for a missing or revoked key, 404 template_not_found for a wrong template name, 422 template_runtime_error when the template fails on the data, 429 rate_limited above the plan’s requests per second, 402 quota_exceeded when the Free plan’s units are used up (a paid plan bills extra units up to its hard cap).
  • Retry safely. Send an Idempotency-Key header with the POST, and repeat the request with the same key when you do not know whether the first attempt arrived: for 24 hours the key returns the first answer instead of rendering and billing again. The answer is stored once the first attempt has been answered, so do not retry while it may still run; and problems below 500 are stored too, so a corrected request needs a new key.

The job around this program

This guide is one program. What the job needs around it, from the template to the limits and the price, is on the page Report PDF generation.

More Go guides

FAQ

Can I poll instead of receiving a webhook?
Yes: GET /renders/{id} until the status is succeeded or failed; the SDKs have waitFor, wait_for, WaitFor and WaitForAsync for it. A webhook saves the requests and reports sooner. See async and batch.
Why must the raw body be used?
The signature covers the bytes on the wire. Parsing and re-serialising JSON may reorder keys, change number formats or escape characters differently, and the HMAC of that text no longer matches.
What is the five-minute tolerance for?
It stops a captured delivery from being replayed later. It also means the clock of your server must be roughly right.

Async render with a webhook in other languages

Start rendering today

The free plan includes 100 units a month and free test renders. Change plans when you need more.