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
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.21 or newer; the program uses the standard library only.
- The template.
revenue-reportfrom the report example, and itsdata.jsonnext 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/formfeedwith your endpoint. While developing,formfeed listenforwards deliveries tolocalhostwithout a tunnel.
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.
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"os"
)
const endpoint = "https://api-eu.formfeed.dev/v1/renders"
// a render or a problem document: both are JSON objects, so one struct decodes either
type render struct {
ID string `json:"id"`
Status string `json:"status"`
Title string `json:"title"`
Detail string `json:"detail"`
}
// send makes one call with the key and decodes the answer
func send(method, url string, body []byte) (int, render) {
request, _ := http.NewRequest(method, url, bytes.NewReader(body))
request.Header.Set("Authorization", "Bearer "+os.Getenv("FORMFEED_API_KEY"))
request.Header.Set("Content-Type", "application/json")
response, err := http.DefaultClient.Do(request)
if err != nil {
panic(err)
}
defer response.Body.Close()
var answer render
json.NewDecoder(response.Body).Decode(&answer)
return response.StatusCode, answer
}
func main() {
data, err := os.ReadFile("data.json")
if err != nil {
panic(err)
}
body, _ := json.Marshal(map[string]any{
"template": "revenue-report",
"data": json.RawMessage(data),
"mode": "async",
"webhook_url": "https://example.com/hooks/formfeed",
"webhook_secret": os.Getenv("FORMFEED_WEBHOOK_SECRET"),
})
status, result := send("POST", endpoint, body)
// every error is a problem document (RFC 9457) with a title and a detail
if status >= 400 {
fmt.Fprintf(os.Stderr, "%s: %s\n", result.Title, result.Detail)
os.Exit(1)
}
fmt.Println(result.ID, result.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.
export FORMFEED_API_KEY=ff_test_...
export FORMFEED_WEBHOOK_SECRET=$(openssl rand -hex 24)
go run main.goWhat is particular about Go
json.RawMessage. The sample data goes into the body as it is on disk, without being decoded into Go types first, so the program works for any template.- One struct for both answers. A render and a problem document are both JSON objects, so a single struct with
titleanddetailbeside the render fields decodes either. - Timeouts.
http.DefaultClienthas none. In a service, give the client aTimeouta little above 60 seconds: a synchronous render answers when the file is done, or after 60 seconds with202while it goes on in the background.
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.
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strconv"
"strings"
"time"
)
var secret = []byte(os.Getenv("FORMFEED_WEBHOOK_SECRET"))
// valid checks "Webhook-Signature: t=<unix seconds>,v1=<hex HMAC-SHA256 of t.body>".
func valid(header string, body []byte) bool {
parts := map[string]string{}
for _, part := range strings.Split(header, ",") {
if key, value, ok := strings.Cut(strings.TrimSpace(part), "="); ok {
parts[key] = value
}
}
timestamp, err := strconv.ParseInt(parts["t"], 10, 64)
if err != nil {
return false
}
if age := time.Now().Unix() - timestamp; age > 300 || age < -300 {
return false
}
mac := hmac.New(sha256.New, secret)
fmt.Fprintf(mac, "%d.%s", timestamp, body)
given, err := hex.DecodeString(parts["v1"])
return err == nil && hmac.Equal(mac.Sum(nil), given)
}
func main() {
http.HandleFunc("/hooks/formfeed", func(w http.ResponseWriter, r *http.Request) {
// the signature covers the bytes on the wire: read the raw body, never re-serialised JSON
body, _ := io.ReadAll(r.Body)
if !valid(r.Header.Get("Webhook-Signature"), body) {
w.WriteHeader(http.StatusUnauthorized)
return
}
var event struct {
Type string `json:"type"`
Data struct {
ID string `json:"id"`
DownloadURL string `json:"download_url"`
} `json:"data"`
}
json.Unmarshal(body, &event)
switch event.Type {
case "render.completed":
fmt.Println("done", event.Data.ID, event.Data.DownloadURL)
case "render.failed":
fmt.Println("failed", event.Data.ID)
}
w.WriteHeader(http.StatusNoContent)
})
http.ListenAndServe(":8080", nil)
}Start the receiver
FORMFEED_WEBHOOK_SECRET=… go run hook.goVerifying in Go
hmac.Equal. It compares the decoded signature bytes in constant time, which also makes upper-case hex harmless.- Read once.
io.ReadAll(r.Body)gives the exact bytes; decode the JSON from that slice afterwards, not from the request body a second time.
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:
{
"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
2xxwithin 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_urlwithoutwebhook_secretis delivered unsigned. For signed deliveries of every render, register an endpoint once in the app or throughPOST /webhooks; it gets its own secret. - Try it locally.
formfeed listen --forward-to http://localhost:8080/hooks/formfeedrelays the events of your test renders to your machine, signed with the session’s own secret rather thanwebhook_secret: start the receiver with that one, whichformfeed listen --print-secretprints (run it before the session, since it ends a running one).formfeed trigger render.completed --template revenue-reportmakes a real test render whose event you watch arrive. The key needs thewebhook:listenscope. 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 stablecodeand therequest_idto quote to support; thetypeURL leads to a page about that error. The list is in the error reference. - The usual ones.
401 unauthorizedfor a missing or revoked key,404 template_not_foundfor a wrong template name,422 template_runtime_errorwhen the template fails on the data,429 rate_limitedabove the plan’s requests per second,402 quota_exceededwhen the Free plan’s units are used up (a paid plan bills extra units up to its hard cap). - Retry safely. Send an
Idempotency-Keyheader 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 issucceededorfailed; the SDKs havewaitForandwait_forfor 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.