Documentation
¶
Overview ¶
Package formfeed is the Go client for the Formfeed API: PDFs and images from templates, HTML, URLs or Markdown, Word and PowerPoint documents from templates, and tools for existing PDFs.
Make a client with your key and render:
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
render, err := client.Renders.Create(ctx, formfeed.RenderRequest{
Template: "invoice",
Data: map[string]any{"customer": map[string]any{"name": "Olvarest GmbH"}},
})
if err != nil {
return err
}
_, err = client.Renders.DownloadFile(ctx, render, "invoice.pdf")
Every call takes a context first; a cancelled context ends the call, and any wait in it, at once. A render is synchronous by default; with Mode "async" it comes back queued and RendersService.WaitFor polls it until it is done. Lists are pages (List) or iterators that follow the cursor (All).
Errors and retries ¶
Every problem the API answers (RFC 9457) is an *Error, whose Code names it (quota_exceeded, template_not_found, …), with the problem's detail as Message, the HTTP Status and the RequestID support asks for:
var ferr *formfeed.Error
if errors.As(err, &ferr) {
log.Printf("%s (%d): %s [%s]", ferr.Code, ferr.Status, ferr.Message, ferr.RequestID)
}
Answers 429 and 503 and network errors are retried up to three times, waiting what Retry-After says, else half a second doubling, plus up to a quarter of a second, never more than 30 seconds. Every call that creates a render sends an Idempotency-Key, so a retry cannot charge twice.
Webhooks ¶
Webhook verifies a delivery's signature and Webhook.Handler is a receiver for net/http.
Everything else ¶
Template authoring, release channels, shared partials and the brand kit have no methods here yet; Client.Request reaches every call of the API with the client's key, retries and errors. The documentation at https://docs.formfeed.dev describes every call.
Index ¶
- Constants
- Variables
- func Ptr[T any](v T) *T
- func VerifyWebhook(secret, signatureHeader string, body []byte) bool
- type AccountService
- type BatchRequest
- type CallOption
- type Client
- type CompressRequest
- type ConvertRequest
- type CreateWebhookRequest
- type Diagnostic
- type EinvoiceReport
- type EinvoicesService
- type Error
- type FileListOptions
- type FilesService
- func (s *FilesService) All(ctx context.Context, opts FileListOptions) iter.Seq2[*LibraryFile, error]
- func (s *FilesService) Delete(ctx context.Context, idOrName string) error
- func (s *FilesService) Get(ctx context.Context, idOrName string) (*LibraryFile, error)
- func (s *FilesService) List(ctx context.Context, opts FileListOptions) (*Page[LibraryFile], error)
- func (s *FilesService) Upload(ctx context.Context, file *Upload) (*LibraryFile, error)
- type FillRequest
- type FormFill
- type InfoRequest
- type Job
- type JobsService
- type LibraryFile
- type MergeRequest
- type Option
- func WithBaseURL(baseURL string) Option
- func WithHTTPClient(client *http.Client) Option
- func WithHeader(name, value string) Option
- func WithJitter(jitter func() time.Duration) Option
- func WithMaxRetries(n int) Option
- func WithRegion(region string) Option
- func WithSleep(sleep func(ctx context.Context, d time.Duration) error) Option
- func WithTimeout(d time.Duration) Option
- type PDFForm
- type PDFFormField
- type PDFInfo
- type PDFPage
- type PDFService
- func (s *PDFService) Compress(ctx context.Context, req CompressRequest, opts ...CallOption) (*Render, error)
- func (s *PDFService) Convert(ctx context.Context, req ConvertRequest, opts ...CallOption) (*Render, error)
- func (s *PDFService) Fill(ctx context.Context, req FillRequest, opts ...CallOption) (*Render, error)
- func (s *PDFService) Info(ctx context.Context, req InfoRequest) (*PDFInfo, error)
- func (s *PDFService) Merge(ctx context.Context, req MergeRequest, opts ...CallOption) (*Render, error)
- func (s *PDFService) Protect(ctx context.Context, req ProtectRequest, opts ...CallOption) (*Render, error)
- func (s *PDFService) Redact(ctx context.Context, req RedactRequest, opts ...CallOption) (*Render, error)
- func (s *PDFService) Split(ctx context.Context, req SplitRequest, opts ...CallOption) (*Render, error)
- func (s *PDFService) ToImage(ctx context.Context, req ToImageRequest, opts ...CallOption) (*Render, error)
- func (s *PDFService) Watermark(ctx context.Context, req WatermarkRequest, opts ...CallOption) (*Render, error)
- type Page
- type Problem
- type ProtectRequest
- type RedactRegion
- type RedactRequest
- type Render
- type RenderError
- type RenderInput
- type RenderListOptions
- type RenderRequest
- type RenderTemplate
- type RendersService
- func (s *RendersService) All(ctx context.Context, opts RenderListOptions) iter.Seq2[*Render, error]
- func (s *RendersService) Batch(ctx context.Context, req BatchRequest, opts ...CallOption) (*Job, error)
- func (s *RendersService) Create(ctx context.Context, req RenderRequest, opts ...CallOption) (*Render, error)
- func (s *RendersService) DeleteOutputs(ctx context.Context, id string) error
- func (s *RendersService) Download(ctx context.Context, render *Render) ([]byte, error)
- func (s *RendersService) DownloadFile(ctx context.Context, render *Render, path string) (int64, error)
- func (s *RendersService) DownloadTo(ctx context.Context, render *Render, w io.Writer) (int64, error)
- func (s *RendersService) Get(ctx context.Context, id string) (*Render, error)
- func (s *RendersService) Input(ctx context.Context, id string) (*RenderInput, error)
- func (s *RendersService) List(ctx context.Context, opts RenderListOptions) (*Page[Render], error)
- func (s *RendersService) WaitFor(ctx context.Context, id string, opts ...WaitOption) (*Render, error)
- type SplitRequest
- type StorageDelivery
- type StorageError
- type Template
- type TemplateListOptions
- type TemplateValidation
- type TemplatesService
- func (s *TemplatesService) All(ctx context.Context, opts TemplateListOptions) iter.Seq2[*Template, error]
- func (s *TemplatesService) Get(ctx context.Context, idOrSlug string) (*Template, error)
- func (s *TemplatesService) List(ctx context.Context, opts TemplateListOptions) (*Page[Template], error)
- func (s *TemplatesService) Schema(ctx context.Context, idOrSlug, version string) (map[string]any, error)
- func (s *TemplatesService) Validate(ctx context.Context, idOrSlug string, req ValidateTemplateRequest) (*TemplateValidation, error)
- type ToImageRequest
- type UpdateWebhookRequest
- type Upload
- type Usage
- type ValidateEinvoiceRequest
- type ValidateTemplateRequest
- type WaitOption
- type WatermarkRequest
- type Webhook
- type WebhookEndpoint
- type WebhookEvent
- type WebhookResend
- type WebhookTest
- type WebhooksService
- func (s *WebhooksService) Create(ctx context.Context, req CreateWebhookRequest) (*WebhookEndpoint, error)
- func (s *WebhooksService) Delete(ctx context.Context, id string) error
- func (s *WebhooksService) List(ctx context.Context) ([]WebhookEndpoint, error)
- func (s *WebhooksService) Resend(ctx context.Context, eventID, endpointID string) (*WebhookResend, error)
- func (s *WebhooksService) Test(ctx context.Context, id string) (*WebhookTest, error)
- func (s *WebhooksService) Update(ctx context.Context, id string, req UpdateWebhookRequest) (*WebhookEndpoint, error)
Examples ¶
Constants ¶
const DefaultWebhookTolerance = 300 * time.Second
DefaultWebhookTolerance is how far a delivery's timestamp may lie from now, either way.
const Version = "0.3.32"
Version is the release of this SDK, the one every Formfeed SDK and package shares. The module's tags carry it (v0.3.x), and the User-Agent names its major and minor number.
Variables ¶
var ErrInvalidSignature = errors.New("formfeed: invalid webhook signature")
ErrInvalidSignature is what Webhook.Parse answers for a delivery whose signature does not match.
Functions ¶
func Ptr ¶
func Ptr[T any](v T) *T
Ptr returns a pointer to v, for the optional fields of a request that a zero value cannot leave out: Dedupe: formfeed.Ptr(false), Opacity: formfeed.Ptr(0.5).
func VerifyWebhook ¶
VerifyWebhook reports whether a delivery is signed with secret, within the default tolerance.
Example ¶
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"strconv"
"time"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
secret := "whsec_mock_secret_123456"
body := []byte(`{"id":"evt_1","type":"render.completed","data":{"id":"rnd_1"}}`)
// what Formfeed sends as Webhook-Signature
now := strconv.FormatInt(time.Now().Unix(), 10)
mac := hmac.New(sha256.New, []byte(secret))
mac.Write([]byte(now + "."))
mac.Write(body)
header := "t=" + now + ",v1=" + hex.EncodeToString(mac.Sum(nil))
fmt.Println(formfeed.VerifyWebhook(secret, header, body))
fmt.Println(formfeed.VerifyWebhook(secret, header, []byte(`{"id":"evt_2"}`)))
}
Output: true false
Types ¶
type AccountService ¶
type AccountService struct {
// contains filtered or unexported fields
}
AccountService reads the key's account and the usage of a billing period.
type BatchRequest ¶
type BatchRequest struct {
Template string `json:"template,omitempty"`
CanaryKey string `json:"canary_key,omitempty"`
Output string `json:"output,omitempty"`
// Items are the renders, each a render request; their Mode is ignored.
Items []RenderRequest `json:"items"`
// Zip packs the outputs of the items that succeeded into one ZIP, Job.ZipURL.
Zip bool `json:"zip,omitempty"`
// WebhookURL receives an event for every item and job.completed or job.failed at the end.
WebhookURL string `json:"webhook_url,omitempty"`
WebhookSecret string `json:"webhook_secret,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Extra map[string]any `json:"-"`
}
BatchRequest is up to 1,000 renders queued as one job. Template, Output and CanaryKey fill in what an item leaves out.
func (BatchRequest) MarshalJSON ¶
func (r BatchRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type CallOption ¶
type CallOption func(*callConfig)
CallOption configures one call.
func WithIdempotencyKey ¶
func WithIdempotencyKey(key string) CallOption
WithIdempotencyKey sends your own Idempotency-Key, an order number for instance, instead of the one the SDK generates for every call that creates a render. A retry of the call, by the SDK or by you with the same key, then cannot charge twice: the API answers the first render again.
type Client ¶
type Client struct {
// Renders creates, reads, waits for and downloads renders, and queues batches.
Renders *RendersService
// Jobs reads batches and waits for them.
Jobs *JobsService
// PDF holds the tools for existing PDFs and the conversion of office documents.
PDF *PDFService
// Einvoices says which rules an e-invoice passed.
Einvoices *EinvoicesService
// Files is the workspace's file library.
Files *FilesService
// Templates reads and checks the workspace's templates.
Templates *TemplatesService
// Webhooks manages the workspace's webhook endpoints. Verify a delivery with [Webhook].
Webhooks *WebhooksService
// Account reads the key's account and the usage of a billing period.
Account *AccountService
// contains filtered or unexported fields
}
Client is the Formfeed API. Make one with NewClient and share it: it is safe for concurrent use.
func NewClient ¶
NewClient makes a client for the key, ff_live_… or ff_test_…:
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
A client without a key, or with an unknown region, answers every call with an *Error of code invalid_request and sends nothing.
Example ¶
package main
import (
"os"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
// eu by default; the key decides between live and test renders
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"),
formfeed.WithRegion("eu"),
formfeed.WithMaxRetries(5),
)
_ = client
}
Output:
func (*Client) Request ¶
func (c *Client) Request(ctx context.Context, method, path string, body, out any, opts ...CallOption) error
Request calls any operation of the API with the client's key, retries and errors, for one without a method here (template authoring, channels, shared partials, the brand kit). path is relative to the base URL and carries its query (/templates/invoice/versions?limit=5); body, when not nil, is sent as JSON; the answer is decoded into out, a pointer, when out is not nil and the answer has a body. No Idempotency-Key is sent unless you pass one.
var brand map[string]any err := client.Request(ctx, http.MethodGet, "/brand", nil, &brand)
Example ¶
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
ctx := context.Background()
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
// the brand kit has no method yet; Request reaches it with the key, retries and errors
var brand struct {
Name string `json:"name"`
Colors map[string]string `json:"colors"`
}
if err := client.Request(ctx, http.MethodGet, "/brand", nil, &brand); err != nil {
log.Fatal(err)
}
fmt.Println(brand.Name, brand.Colors["primary"])
}
Output:
type CompressRequest ¶
type CompressRequest struct {
Source string `json:"source,omitempty"`
File *Upload `json:"-"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
CompressRequest makes a PDF smaller.
func (CompressRequest) MarshalJSON ¶
func (r CompressRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type ConvertRequest ¶
type ConvertRequest struct {
Source string `json:"source,omitempty"`
File *Upload `json:"-"`
// PageRanges are the pages to convert, such as 1-3,5; all when empty.
PageRanges string `json:"page_ranges,omitempty"`
// Landscape is for spreadsheets and documents without their own page setup.
Landscape bool `json:"landscape,omitempty"`
// SinglePageSheets puts each spreadsheet sheet on one page.
SinglePageSheets bool `json:"single_page_sheets,omitempty"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
ConvertRequest converts an office document to a PDF: a File (Word, Excel, PowerPoint, OpenDocument, RTF or HTML, up to 20 MB, never kept) or the Source of a Word or PowerPoint template render.
func (ConvertRequest) MarshalJSON ¶
func (r ConvertRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type CreateWebhookRequest ¶
type CreateWebhookRequest struct {
// URL is an https URL on a public host.
URL string `json:"url"`
// Events are the events to receive; render.completed, render.failed, job.completed and
// job.failed when nil. quota.* and storage.* arrive only when listed.
Events []string `json:"events,omitempty"`
// Environments are live and test, both when nil.
Environments []string `json:"environments,omitempty"`
Description string `json:"description,omitempty"`
Extra map[string]any `json:"-"`
}
CreateWebhookRequest registers an endpoint.
func (CreateWebhookRequest) MarshalJSON ¶
func (r CreateWebhookRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type Diagnostic ¶
type Diagnostic struct {
// Severity is error, warning or info.
Severity string `json:"severity"`
Code string `json:"code"`
Message string `json:"message"`
// Location is where in the template source, line and column from 1.
Location *struct {
Line int `json:"line"`
Column int `json:"column"`
} `json:"location"`
// Path is where in the data, for data errors: data.invoice.lines[0].qty.
Path string `json:"path"`
// Part and Paragraph place a finding in a Word or PowerPoint template.
Part string `json:"part"`
Paragraph int `json:"paragraph"`
}
Diagnostic is one finding of a check. Only error findings make a validation fail.
type EinvoiceReport ¶
type EinvoiceReport struct {
ID string `json:"id"`
// Result is passed, failed or not_checked, and takes new values.
Result string `json:"result"`
// Reason says why a file was not checked; Explanation says it in a sentence.
Reason string `json:"reason"`
Explanation string `json:"explanation"`
Validator string `json:"validator"`
Rules string `json:"rules"`
Scenario string `json:"scenario"`
Profile string `json:"profile"`
// Checks are what the file was held to, each with its own result.
Checks []struct {
// Kind is syntax, schema, rules or container.
Kind string `json:"kind"`
Name string `json:"name"`
// Result is passed, failed or not_run.
Result string `json:"result"`
Messages []struct {
Part string `json:"part"`
Severity string `json:"severity"`
Rule string `json:"rule"`
Message string `json:"message"`
Location string `json:"location"`
} `json:"messages"`
} `json:"checks"`
Truncated bool `json:"truncated"`
Versions map[string]string `json:"versions"`
XMLSHA256 string `json:"xml_sha256"`
PDFSHA256 string `json:"pdf_sha256"`
ValidatedAt string `json:"validated_at"`
// Raw is the report as the API sent it.
Raw json.RawMessage `json:"-"`
}
EinvoiceReport says which rules an e-invoice passed, by which validator and release, and which bytes it judged; not whether the document is a proper invoice for VAT purposes. Raw holds the members not typed here (source, route, display, allowance).
func (*EinvoiceReport) UnmarshalJSON ¶
func (r *EinvoiceReport) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a report leniently and keeps it in Raw.
type EinvoicesService ¶
type EinvoicesService struct {
// contains filtered or unexported fields
}
EinvoicesService says which rules an e-invoice passed. Needs the einvoice:validate scope.
func (*EinvoicesService) Validate ¶
func (s *EinvoicesService) Validate(ctx context.Context, req ValidateEinvoiceRequest, opts ...CallOption) (*EinvoiceReport, error)
Validate judges an e-invoice: a render of this workspace's own e-invoice (RenderID), answered from the report it keeps, free; or an XML Formfeed did not make (File), which takes one of the organisation's validations of the day. It sends an Idempotency-Key, as RendersService.Create does.
type Error ¶
type Error struct {
// Code names the problem, as the docs list it under https://docs.formfeed.dev/errors.
Code string
// Message is the problem's detail, else its title, else "HTTP <status>".
Message string
// Status is the HTTP status, 0 when there was no answer.
Status int
// Problem is the problem document as the API sent it; nil when the answer had none.
Problem *Problem
// RequestID is the X-Request-Id the API answered with, which support asks for.
RequestID string
// Err is the cause of a failure on this side, such as the network error; nil for a problem.
Err error
}
Error is every problem the API answers (RFC 9457) and every failure on this side, one type for all of them:
var ferr *formfeed.Error
if errors.As(err, &ferr) && ferr.Code == "quota_exceeded" { … }
Code is the problem's code (quota_exceeded, template_not_found, …), else http_<status>; for what went wrong before an answer it is network_error, timeout, not_ready, download_failed, invalid_response or invalid_request. A cancelled or expired context is not an Error: the call answers ctx.Err() itself.
Example ¶
package main
import (
"context"
"errors"
"log"
"os"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
ctx := context.Background()
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
_, err := client.Renders.Create(ctx, formfeed.RenderRequest{Template: "invoice"})
var ferr *formfeed.Error
switch {
case errors.As(err, &ferr) && ferr.Code == "quota_exceeded":
log.Print("the period has no units left")
case errors.As(err, &ferr):
log.Printf("%s (%d): %s [%s]", ferr.Code, ferr.Status, ferr.Message, ferr.RequestID)
case err != nil:
log.Print(err) // the context ended
}
}
Output:
type FileListOptions ¶
type FileListOptions struct {
// Prefix keeps the names that start with it (brand/).
Prefix string
Limit int
Cursor string
}
FileListOptions narrows FilesService.List and All.
type FilesService ¶
type FilesService struct {
// contains filtered or unexported fields
}
FilesService is the workspace's file library: images and PDFs a template names with asset('logo.png'), and the sources of image watermarks and merges. Needs file:read, file:write or file:delete. Files are served without a signature, so keep confidential documents out of it.
func (*FilesService) All ¶
func (s *FilesService) All(ctx context.Context, opts FileListOptions) iter.Seq2[*LibraryFile, error]
All iterates over every file the options match, page after page; an error ends it as its last value.
func (*FilesService) Delete ¶
func (s *FilesService) Delete(ctx context.Context, idOrName string) error
Delete removes a file and its bytes; templates that name it render a missing image afterwards.
func (*FilesService) Get ¶
func (s *FilesService) Get(ctx context.Context, idOrName string) (*LibraryFile, error)
Get reads a file by its id (fil_…) or name.
func (*FilesService) List ¶
func (s *FilesService) List(ctx context.Context, opts FileListOptions) (*Page[LibraryFile], error)
List reads one page of files, newest first.
func (*FilesService) Upload ¶
func (s *FilesService) Upload(ctx context.Context, file *Upload) (*LibraryFile, error)
Upload adds a file under its Name; one of the same name is replaced in place and keeps its URL.
type FillRequest ¶
type FillRequest struct {
Source string `json:"source,omitempty"`
File *Upload `json:"-"`
// Fields are the values by full name: a string (or number) for a text field, a bool for a
// check box, an option for a choice or radio group, a []string for a list box.
Fields map[string]any `json:"fields,omitzero"`
// Flatten draws the values into the pages and removes the fields.
Flatten bool `json:"flatten,omitempty"`
// Strict fails on a name the form lacks or a value its field does not take; true when nil,
// Ptr(false) lists both in Render.Form instead.
Strict *bool `json:"strict,omitempty"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
FillRequest fills a form's fields by their full names, as PDFService.Info lists them, or with Flatten draws the values into the pages. The values are never stored.
func (FillRequest) MarshalJSON ¶
func (r FillRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type FormFill ¶
type FormFill struct {
Filled int `json:"filled"`
// Skipped are the fields left out, with the reason unknown or invalid.
Skipped []struct {
Field string `json:"field"`
Reason string `json:"reason"`
} `json:"skipped"`
// Warnings are the calculations and display formats of the form that no viewer has run.
Warnings []struct {
Field string `json:"field"`
Code string `json:"code"`
} `json:"warnings"`
// XFARemoved is true when the form was a hybrid whose XFA part was removed.
XFARemoved bool `json:"xfa_removed"`
}
FormFill is what a fill did. Its entries name fields, never their values.
type InfoRequest ¶
type InfoRequest struct {
Source string `json:"source,omitempty"`
File *Upload `json:"-"`
Extra map[string]any `json:"-"`
}
InfoRequest names the PDF PDFService.Info reads.
func (InfoRequest) MarshalJSON ¶
func (r InfoRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type Job ¶
type Job struct {
ID string `json:"id"`
// Type is single or batch.
Type string `json:"type"`
// Status is queued, processing, completed, partially_failed or failed.
Status string `json:"status"`
Total int `json:"total"`
Succeeded int `json:"succeeded"`
Failed int `json:"failed"`
// ZipURL is the link to the ZIP of a batch that asked for one, once it has finished.
ZipURL string `json:"zip_url"`
ZipExpiresAt string `json:"zip_expires_at"`
Storage *StorageDelivery `json:"storage"`
// Items are the renders, in the order of the request.
Items []Render `json:"items"`
Meta map[string]any `json:"meta"`
CreatedAt string `json:"created_at"`
CompletedAt string `json:"completed_at"`
// Raw is the job as the API sent it.
Raw json.RawMessage `json:"-"`
}
Job is a batch, or a render queued with its own webhook URL: its renders in the order of the request and, once they are done, a ZIP of their files.
func (*Job) UnmarshalJSON ¶
UnmarshalJSON reads a job leniently and keeps it in Raw.
type JobsService ¶
type JobsService struct {
// contains filtered or unexported fields
}
JobsService reads batches and waits for them.
func (*JobsService) Get ¶
Get reads a job with its counts, every item as a render, and the ZIP's link once a batch with Zip has finished.
func (*JobsService) WaitFor ¶
func (s *JobsService) WaitFor(ctx context.Context, id string, opts ...WaitOption) (*Job, error)
WaitFor polls a job until no render of it is queued or running, every 2 seconds for at most 600 seconds (WithPollInterval, WithWaitTimeout), and answers an *Error of code timeout after that.
type LibraryFile ¶
type LibraryFile struct {
// ID is the file id, fil_….
ID string `json:"id"`
// Name is the library name, the address a template names (logo.png, brand/header.svg).
Name string `json:"name"`
ContentType string `json:"content_type"`
Bytes int64 `json:"bytes"`
SHA256 string `json:"sha256"`
// URL is the CDN URL, the one asset(name) produces.
URL string `json:"url"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
// Raw is the file as the API sent it.
Raw json.RawMessage `json:"-"`
}
LibraryFile is a file of the workspace's library: an image or PDF a template names, served at URL.
func (*LibraryFile) UnmarshalJSON ¶
func (f *LibraryFile) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a file leniently and keeps it in Raw.
type MergeRequest ¶
type MergeRequest struct {
// Sources are render ids, library file ids or library names; 2 to 50 of them.
Sources []string `json:"sources"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
MergeRequest joins PDFs in the order given.
func (MergeRequest) MarshalJSON ¶
func (r MergeRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type Option ¶
type Option func(*clientConfig)
Option configures a Client.
func WithBaseURL ¶
WithBaseURL sets the full base URL with /v1, for a local or another gateway (http://localhost:8787/v1).
func WithHTTPClient ¶
WithHTTPClient sends over your own client, with its own transport and time limits; WithTimeout then has no effect.
func WithHeader ¶
WithHeader sends a header with every request, after the SDK's own, which it replaces.
func WithJitter ¶
WithJitter replaces the random part of a retry's wait, from 0 to 250 ms (a value outside that is held to it). Tests pass a constant.
func WithMaxRetries ¶
WithMaxRetries sets how often a call is retried on 429, 503 and network errors: 3 by default, 0 turns retries off.
func WithRegion ¶
WithRegion picks the API host: "eu" (the default) or "us". Ignored when WithBaseURL is given.
func WithSleep ¶
WithSleep replaces how the client waits between retries and polls. The function must return ctx.Err() at once when ctx ends; tests pass one that records the waits and returns nil.
func WithTimeout ¶
WithTimeout limits every request of the client the SDK makes itself, the download of its body included: 120 seconds by default; 0 sets no limit.
type PDFForm ¶
type PDFForm struct {
// Type is acroform, hybrid (with an XFA part) or xfa (which Fill refuses); empty without a form.
Type string `json:"type"`
// Signed is true when the form holds a signature; Fill refuses such a file.
Signed bool `json:"signed"`
Fields []PDFFormField `json:"fields"`
}
PDFForm is the form of a PDF.
type PDFFormField ¶
type PDFFormField struct {
// Name is the full name, parts joined by dots, which Fill takes.
Name string `json:"name"`
// Label is what the field is for, from its tooltip.
Label string `json:"label"`
// Type is text, checkbox, radio, dropdown, listbox, signature or button.
Type string `json:"type"`
// Value is a string, a bool or a []any of strings; nil when unset.
Value any `json:"value"`
// Options are what Fill takes for a choice, a radio group or a check box with several
// on-values.
Options []string `json:"options"`
Required bool `json:"required"`
Readonly bool `json:"readonly"`
Calculated bool `json:"calculated"`
Format string `json:"format"`
Pages []int `json:"pages"`
}
PDFFormField is one field of a form.
type PDFInfo ¶
type PDFInfo struct {
// Source is the render id or library file the info is of, or the upload's name.
Source string `json:"source"`
PageCount int `json:"page_count"`
Pages []PDFPage `json:"pages"`
Encrypted bool `json:"encrypted"`
// Metadata holds title, author, subject, producer and creator.
Metadata map[string]any `json:"metadata"`
// Form is nil when the file needs a password to open.
Form *PDFForm `json:"form"`
// Raw is the info as the API sent it.
Raw json.RawMessage `json:"-"`
}
PDFInfo is what a PDF holds: its pages and their sizes, whether it is encrypted, its metadata, and its form with every field's full name, the names PDFService.Fill takes.
func (*PDFInfo) UnmarshalJSON ¶
UnmarshalJSON reads the info leniently and keeps it in Raw.
type PDFPage ¶
type PDFPage struct {
WidthPt float64 `json:"width_pt"`
HeightPt float64 `json:"height_pt"`
WidthMM float64 `json:"width_mm"`
HeightMM float64 `json:"height_mm"`
}
PDFPage is the size of one page, in points and millimetres.
type PDFService ¶
type PDFService struct {
// contains filtered or unexported fields
}
PDFService holds the tools for existing PDFs: on the output of an earlier render, a PDF of the file library, or, for Info, Split, Compress, ToImage, Redact and Fill, an upload, which is never stored. Every tool but Info answers a new render, on the Starter plan and above: Merge, Protect, Watermark, Split, Compress, Redact and Fill cost 0.5 units each on live keys, ToImage one unit per picture; Info is free. Each tool that renders sends an Idempotency-Key, as RendersService.Create does.
func (*PDFService) Compress ¶
func (s *PDFService) Compress(ctx context.Context, req CompressRequest, opts ...CallOption) (*Render, error)
Compress makes a PDF smaller; the render keeps the source when it cannot.
func (*PDFService) Convert ¶
func (s *PDFService) Convert(ctx context.Context, req ConvertRequest, opts ...CallOption) (*Render, error)
Convert converts an office document to a PDF render (Starter plan and above).
func (*PDFService) Fill ¶
func (s *PDFService) Fill(ctx context.Context, req FillRequest, opts ...CallOption) (*Render, error)
Fill fills a form's fields by their full names and keeps it fillable, or with Flatten draws the values into the pages. Render.Form says what it did.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
ctx := context.Background()
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
form, err := formfeed.UploadFromFile("form.pdf")
if err != nil {
log.Fatal(err)
}
info, err := client.PDF.Info(ctx, formfeed.InfoRequest{File: form})
if err != nil {
log.Fatal(err)
}
for _, field := range info.Form.Fields {
fmt.Println(field.Name, field.Type)
}
filled, err := client.PDF.Fill(ctx, formfeed.FillRequest{
File: form,
Fields: map[string]any{"name": "Max Mustermann", "accepted": true},
Flatten: true,
})
if err != nil {
log.Fatal(err)
}
merged, err := client.PDF.Merge(ctx, formfeed.MergeRequest{Sources: []string{filled.ID, "terms.pdf"}})
if err != nil {
log.Fatal(err)
}
fmt.Println(merged.DownloadURL)
}
Output:
func (*PDFService) Info ¶
func (s *PDFService) Info(ctx context.Context, req InfoRequest) (*PDFInfo, error)
Info reads a PDF's page count, page sizes, encryption, metadata and form, with every field's name, type, value and options, which is how a form's names are found for Fill. Free; it creates no render.
func (*PDFService) Merge ¶
func (s *PDFService) Merge(ctx context.Context, req MergeRequest, opts ...CallOption) (*Render, error)
Merge joins PDFs in the order of Sources.
func (*PDFService) Protect ¶
func (s *PDFService) Protect(ctx context.Context, req ProtectRequest, opts ...CallOption) (*Render, error)
Protect encrypts a PDF with AES-256.
func (*PDFService) Redact ¶
func (s *PDFService) Redact(ctx context.Context, req RedactRequest, opts ...CallOption) (*Render, error)
Redact removes what lies under the rectangles and every place a text stands, from the file itself, and reads the result again: text still there fails the render with redaction_incomplete, which names regions and texts by number, never a text.
func (*PDFService) Split ¶
func (s *PDFService) Split(ctx context.Context, req SplitRequest, opts ...CallOption) (*Render, error)
Split cuts a PDF into parts: a ZIP of the parts, or the PDF itself for one part.
func (*PDFService) ToImage ¶
func (s *PDFService) ToImage(ctx context.Context, req ToImageRequest, opts ...CallOption) (*Render, error)
ToImage draws pages as PNG or JPEG pictures: one page answers the picture, several a ZIP of them.
func (*PDFService) Watermark ¶
func (s *PDFService) Watermark(ctx context.Context, req WatermarkRequest, opts ...CallOption) (*Render, error)
Watermark stamps a text or a library image on the pages.
type Page ¶
Page is one page of a list, newest first, and the cursor of the next, empty on the last.
type Problem ¶
type Problem struct {
Type string `json:"type"`
Title string `json:"title"`
Status int `json:"status"`
Detail string `json:"detail"`
Code string `json:"code"`
RequestID string `json:"request_id"`
// RenderID names the failed render of a problem that a render's failure answered.
RenderID string `json:"render_id"`
// Members is the whole document, decoded.
Members map[string]any `json:"-"`
// Raw is the document as the API sent it.
Raw json.RawMessage `json:"-"`
}
Problem is an RFC 9457 problem document. Members holds every member as sent, those a problem adds beside the standard ones included: errors, index, feature, limit, einvoice, accessibility, …
func (*Problem) UnmarshalJSON ¶
UnmarshalJSON reads a problem leniently, keeping every member in Members.
type ProtectRequest ¶
type ProtectRequest struct {
Source string `json:"source,omitempty"`
// UserPassword is needed to open the document.
UserPassword string `json:"user_password,omitempty"`
// OwnerPassword lifts the restrictions; a random one nobody knows when empty.
OwnerPassword string `json:"owner_password,omitempty"`
// Permissions are what a reader without the owner password may do: print, copy, modify,
// annotate. A nil list allows all four, an empty one none.
Permissions []string `json:"permissions,omitzero"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
ProtectRequest encrypts a PDF with AES-256.
func (ProtectRequest) MarshalJSON ¶
func (r ProtectRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type RedactRegion ¶
type RedactRegion struct {
// Page is the page number, from 1.
Page int `json:"page"`
X float64 `json:"x"`
Y float64 `json:"y"`
Width float64 `json:"width"`
Height float64 `json:"height"`
}
RedactRegion is a rectangle as a viewer shows the page: points from its top-left corner, y running down.
type RedactRequest ¶
type RedactRequest struct {
Source string `json:"source,omitempty"`
File *Upload `json:"-"`
Regions []RedactRegion `json:"regions,omitempty"`
// Text are texts to remove wherever they stand, found whatever their whitespace; never stored.
Text []string `json:"text,omitempty"`
// MatchCase finds a text only in the case it is written in.
MatchCase bool `json:"match_case,omitempty"`
// WholeWords finds a text only where a word boundary stands on each side of it.
WholeWords bool `json:"whole_words,omitempty"`
// Fill is the hex colour of the box drawn over each redaction, black when empty.
Fill string `json:"fill,omitempty"`
// NoFill draws no box at all: it sends fill as null.
NoFill bool `json:"-"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
RedactRequest removes what lies under Regions and every place a Text stands, from the file itself; give Regions, Text or both.
func (RedactRequest) MarshalJSON ¶
func (r RedactRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members, and fill as null for NoFill.
type Render ¶
type Render struct {
// ID is the render id, rnd_ and 32 hexadecimal digits.
ID string `json:"id"`
// Status is queued, rendering, succeeded or failed.
Status string `json:"status"`
// Output is pdf, png, jpg, webp, docx, pptx, or zip for a tool that made several files.
Output string `json:"output"`
// DownloadURL is the link to the file; empty while queued, for a failed render and once the
// output was deleted or expired. A signed link works for seven days at most: read the render
// again for a fresh one.
DownloadURL string `json:"download_url"`
// ExpiresAt is when DownloadURL stops working.
ExpiresAt string `json:"expires_at"`
// Bytes is the size of the file.
Bytes int64 `json:"bytes"`
// PageCount is the pages of a PDF; 0 for other outputs and while queued.
PageCount int `json:"page_count"`
// Units is what the render cost; 0 for test keys and an answer from the dedup cache.
Units float64 `json:"units"`
// Region is the region the render ran in, eu.
Region string `json:"region"`
// Environment is live or test, after the key that made it.
Environment string `json:"environment"`
// Template is the template and version that rendered; nil for HTML, URL, Markdown and PDF
// tool renders and for an answer from the dedup cache.
Template *RenderTemplate `json:"template"`
// EngineVersion says what produced the file, for reproducibility; empty until it succeeded.
EngineVersion string `json:"engine_version"`
// TemplateChecksum is the checksum of the template version that rendered.
TemplateChecksum string `json:"template_checksum"`
// OutputSHA256 is the SHA-256 of the file, as hexadecimal.
OutputSHA256 string `json:"output_sha256"`
// Deduplicated is true when the answer came from the dedup cache.
Deduplicated bool `json:"deduplicated"`
// Storage is the copy to the workspace's own bucket; nil when none applies.
Storage *StorageDelivery `json:"storage"`
// Einvoice is the e-invoice report: profile, flavour, validation, display; nil for a render
// that made none. A failed render keeps it too, which is where it says why.
Einvoice map[string]any `json:"einvoice"`
// Accessibility is the validator's PDF/UA-1 verdict; nil unless the render set settings.pdf.ua.
Accessibility map[string]any `json:"accessibility"`
// PDFA is the validator's PDF/A verdict; nil unless the render set settings.pdf.pdfa.
PDFA map[string]any `json:"pdfa"`
// Form is what a fill did; nil for every render but those of PDFService.Fill.
Form *FormFill `json:"form"`
// Timings are the milliseconds per phase of a render that succeeded (compile_ms, render_ms, …).
Timings map[string]int64 `json:"timings"`
// Error is why a failed render failed. It is a value, so it reads without a nil check: its Code
// is empty unless Status is failed, and empty too where the API named no reason.
Error RenderError `json:"error"`
// Meta is the meta of the request, unchanged.
Meta map[string]any `json:"meta"`
CreatedAt string `json:"created_at"`
CompletedAt string `json:"completed_at"`
// Raw is the render as the API sent it.
Raw json.RawMessage `json:"-"`
}
Render is a render: a template, HTML, URL or Markdown render, or the result of a PDF tool.
func (*Render) Finished ¶
Finished reports whether the render succeeded or failed, after which nothing changes any more.
func (*Render) UnmarshalJSON ¶
UnmarshalJSON reads a render leniently and keeps it in Raw.
type RenderError ¶
type RenderError struct {
Code string `json:"code"`
Message string `json:"message"`
Details map[string]any `json:"-"`
}
RenderError is the error a failed render stored: its code and English message, and in Details every member, those that say more included.
func (*RenderError) UnmarshalJSON ¶
func (e *RenderError) UnmarshalJSON(data []byte) error
UnmarshalJSON reads the error leniently, keeping every member in Details.
type RenderInput ¶
type RenderInput struct {
RenderID string `json:"render_id"`
// Template is the template, version and channel; nil for an ad-hoc render.
Template *RenderTemplate `json:"template"`
Data map[string]any `json:"data"`
HTML string `json:"html"`
Markdown string `json:"markdown"`
URL string `json:"url"`
Engine string `json:"engine"`
Locale string `json:"locale"`
Output string `json:"output"`
Settings map[string]any `json:"settings"`
Filename string `json:"filename"`
Post map[string]any `json:"post"`
Meta map[string]any `json:"meta"`
Environment string `json:"environment"`
CreatedAt string `json:"created_at"`
// Raw is the request as the API sent it.
Raw json.RawMessage `json:"-"`
}
RenderInput is the stored request of a render, to render it again: a template render carries Template and Data, an ad-hoc one HTML, URL or Markdown. Passwords are never included.
func (*RenderInput) UnmarshalJSON ¶
func (r *RenderInput) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a render's request leniently and keeps it in Raw.
type RenderListOptions ¶
type RenderListOptions struct {
// Template is a slug, tpl_… id or UUID.
Template string
// Status is queued, rendering, succeeded or failed.
Status string
// Environment is live or test.
Environment string
// Since and Until bound created_at, ISO 8601 with an offset (2026-11-01T00:00:00Z).
Since string
Until string
Limit int
// Cursor is the NextCursor of the page before; All starts there.
Cursor string
}
RenderListOptions narrows RendersService.List and All.
type RenderRequest ¶
type RenderRequest struct {
// Template is the template by slug or id (tpl_…).
Template string `json:"template,omitempty"`
// Version is published (the default), a release channel such as staging, latest (test keys
// only) or a version number.
Version string `json:"version,omitempty"`
// HTML is ad-hoc HTML, at most 5 MB; with an Engine a template over Data.
HTML string `json:"html,omitempty"`
// URL is a public https page to print.
URL string `json:"url,omitempty"`
// Markdown is a Markdown document, at most 1 MB; with an Engine a template over Data first.
Markdown string `json:"markdown,omitempty"`
// Engine is the template language of HTML or Markdown: jinja2, liquid or handlebars.
Engine string `json:"engine,omitempty"`
// Data is what the template renders with.
Data map[string]any `json:"data,omitzero"`
// Output is pdf, png, jpg, webp, docx or pptx; left out, the template decides.
Output string `json:"output,omitempty"`
// Settings are merged over the template's: paper, margins, pdf (ua, pdfa, metadata), image,
// markdown, … as the settings reference lists them.
Settings map[string]any `json:"settings,omitzero"`
// Filename names the output file.
Filename string `json:"filename,omitempty"`
// ExpiresIn is the seconds until the output expires; it can only shorten the retention.
ExpiresIn int `json:"expires_in,omitempty"`
// Access is signed (a link that works for seven days at most) or public.
Access string `json:"access,omitempty"`
// Mode is sync (the default: the answer is the finished render) or async (the answer is the
// queued render; wait for it with RendersService.WaitFor).
Mode string `json:"mode,omitempty"`
// Locale formats dates and numbers and selects the translation dictionary.
Locale string `json:"locale,omitempty"`
// WebhookURL receives render.completed or render.failed for this render.
WebhookURL string `json:"webhook_url,omitempty"`
// WebhookSecret signs the deliveries to WebhookURL; 16 to 200 characters.
WebhookSecret string `json:"webhook_secret,omitempty"`
// Meta is your own data, returned unchanged with the render and in its webhook events.
Meta map[string]any `json:"meta,omitzero"`
// Region is the workspace's region; leave it out.
Region string `json:"region,omitempty"`
// Dedupe answers a request identical to one of the last 24 hours from the earlier render at
// zero units; true by default, Ptr(false) always renders.
Dedupe *bool `json:"dedupe,omitempty"`
// CanaryKey decides a channel's canary split: renders with the same value land on the same
// version.
CanaryKey string `json:"canary_key,omitempty"`
// ValidateData checks Data against the template's stored schema before anything is rendered.
ValidateData bool `json:"validate_data,omitempty"`
// Post is the post-processing of a PDF: merge_after, watermark, password and einvoice.
Post map[string]any `json:"post,omitzero"`
// Storage is the copy for the workspace's own bucket: false leaves it out, a map with key names
// its object.
Storage any `json:"storage,omitempty"`
// Extra holds members this release does not know yet.
Extra map[string]any `json:"-"`
}
RenderRequest is one render. Send exactly one source: Template, HTML, URL or Markdown.
func (RenderRequest) MarshalJSON ¶
func (r RenderRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type RenderTemplate ¶
type RenderTemplate struct {
// ID is the template id, tpl_…, which a render request takes as Template.
ID string `json:"id"`
Slug string `json:"slug"`
Version int `json:"version"`
// Channel is the release channel the version came from; empty when the request named a version
// number or latest.
Channel string `json:"channel"`
// Canary is true when the channel's canary share picked this version.
Canary bool `json:"canary"`
}
RenderTemplate is the template and version of a render.
type RendersService ¶
type RendersService struct {
// contains filtered or unexported fields
}
RendersService creates, reads, waits for and downloads renders, and queues batches.
func (*RendersService) All ¶
func (s *RendersService) All(ctx context.Context, opts RenderListOptions) iter.Seq2[*Render, error]
All iterates over every render the options match, reading page after page as the loop asks for them. An error ends the iteration as its last value:
for render, err := range client.Renders.All(ctx, formfeed.RenderListOptions{Status: "failed"}) {
if err != nil {
return err
}
fmt.Println(render.ID, render.CreatedAt)
}
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
ctx := context.Background()
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
for render, err := range client.Renders.All(ctx, formfeed.RenderListOptions{Status: "failed", Since: "2026-11-01T00:00:00Z"}) {
if err != nil {
log.Fatal(err)
}
fmt.Println(render.ID, render.Error.Code)
}
}
Output:
func (*RendersService) Batch ¶
func (s *RendersService) Batch(ctx context.Context, req BatchRequest, opts ...CallOption) (*Job, error)
Batch queues up to 1,000 renders as one job, whose renders keep the order of the items. It sends an Idempotency-Key as Create does.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
ctx := context.Background()
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
job, err := client.Renders.Batch(ctx, formfeed.BatchRequest{
Template: "certificate",
Items: []formfeed.RenderRequest{
{Data: map[string]any{"name": "Max Mustermann"}},
{Data: map[string]any{"name": "Erika Mustermann"}},
},
Zip: true,
})
if err != nil {
log.Fatal(err)
}
job, err = client.Jobs.WaitFor(ctx, job.ID)
if err != nil {
log.Fatal(err)
}
fmt.Println(job.Status, job.ZipURL)
}
Output:
func (*RendersService) Create ¶
func (s *RendersService) Create(ctx context.Context, req RenderRequest, opts ...CallOption) (*Render, error)
Create renders a template, HTML, a URL or Markdown. It is synchronous by default, so the answer is the finished render; with Mode "async" it is the queued render, which WaitFor follows. Every call sends an Idempotency-Key, generated unless you pass WithIdempotencyKey, and its retries the same one, so a retry cannot charge twice.
Example ¶
package main
import (
"context"
"log"
"os"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
ctx := context.Background()
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
render, err := client.Renders.Create(ctx, formfeed.RenderRequest{
Template: "invoice",
Data: map[string]any{
"customer": map[string]any{"name": "Olvarest GmbH"},
"total": 1428.00,
},
}, formfeed.WithIdempotencyKey("order-1042"))
if err != nil {
log.Fatal(err)
}
if _, err := client.Renders.DownloadFile(ctx, render, "invoice.pdf"); err != nil {
log.Fatal(err)
}
}
Output:
func (*RendersService) DeleteOutputs ¶
func (s *RendersService) DeleteOutputs(ctx context.Context, id string) error
DeleteOutputs removes the stored files of a render before they expire. Needs the file:delete scope.
func (*RendersService) Download ¶
Download reads the output of a finished render into memory. It follows the signed link, without the API key, and answers an *Error of code not_ready when the render has no output.
func (*RendersService) DownloadFile ¶
func (s *RendersService) DownloadFile(ctx context.Context, render *Render, path string) (int64, error)
DownloadFile writes the output of a finished render to a file, which it creates or truncates, and answers the bytes written. A download that fails leaves no file behind.
func (*RendersService) DownloadTo ¶
func (s *RendersService) DownloadTo(ctx context.Context, render *Render, w io.Writer) (int64, error)
DownloadTo streams the output of a finished render into w and answers the bytes written.
func (*RendersService) Get ¶
Get reads a render. While its output is stored the answer carries a fresh DownloadURL.
func (*RendersService) Input ¶
func (s *RendersService) Input(ctx context.Context, id string) (*RenderInput, error)
Input reads the stored request of a render, to render it again. Needs the render:input scope; answers render_input_expired (410) when the workspace keeps no requests or the period ended.
func (*RendersService) List ¶
func (s *RendersService) List(ctx context.Context, opts RenderListOptions) (*Page[Render], error)
List reads one page of renders, newest first.
func (*RendersService) WaitFor ¶
func (s *RendersService) WaitFor(ctx context.Context, id string, opts ...WaitOption) (*Render, error)
WaitFor polls a render until it succeeded or failed, every second for at most 120 seconds (WithPollInterval, WithWaitTimeout), and answers an *Error of code timeout after that. A failed render is an answer, not an error: look at its Status and Error.
Example ¶
package main
import (
"context"
"fmt"
"log"
"os"
"time"
formfeed "github.com/formfeed-dev/formfeed-go"
)
func main() {
ctx := context.Background()
client := formfeed.NewClient(os.Getenv("FORMFEED_API_KEY"))
queued, err := client.Renders.Create(ctx, formfeed.RenderRequest{HTML: "<h1>Report</h1>", Mode: "async"})
if err != nil {
log.Fatal(err)
}
render, err := client.Renders.WaitFor(ctx, queued.ID, formfeed.WithWaitTimeout(2*time.Minute))
if err != nil {
log.Fatal(err)
}
if render.Status == "failed" {
log.Fatalf("%s: %s", render.Error.Code, render.Error.Message)
}
pdf, err := client.Renders.Download(ctx, render)
if err != nil {
log.Fatal(err)
}
fmt.Println(len(pdf), "bytes")
}
Output:
type SplitRequest ¶
type SplitRequest struct {
Source string `json:"source,omitempty"`
File *Upload `json:"-"`
// Every is the pages per part.
Every int `json:"every,omitempty"`
// Ranges are one page selection per part, such as 1-3,5 or 4- (page 4 to the last).
Ranges []string `json:"ranges,omitempty"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
SplitRequest cuts a PDF into parts, Every pages each or one per entry of Ranges.
func (SplitRequest) MarshalJSON ¶
func (r SplitRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type StorageDelivery ¶
type StorageDelivery struct {
// Status is pending, delivered or failed.
Status string `json:"status"`
Bucket string `json:"bucket"`
Key string `json:"key"`
// URL is the object below the connection's public base URL; empty without one.
URL string `json:"url"`
// Reason says why a copy failed or was not made.
Reason string `json:"reason"`
Error *StorageError `json:"error"`
}
StorageDelivery is where the copy to the workspace's own bucket goes and how far it got.
type StorageError ¶
type StorageError struct {
Code string `json:"code"`
HTTPStatus int `json:"http_status"`
Message string `json:"message"`
}
StorageError is the provider's answer to a failed copy.
type Template ¶
type Template struct {
// ID is the template id, tpl_….
ID string `json:"id"`
Slug string `json:"slug"`
Name string `json:"name"`
Description string `json:"description"`
// Kind is pdf, image, docx or pptx.
Kind string `json:"kind"`
// Engine is jinja2, liquid or handlebars.
Engine string `json:"engine"`
Tags []string `json:"tags"`
// PublishedVersion is the number of the published version; 0 while none is.
PublishedVersion int `json:"published_version"`
LatestVersion int `json:"latest_version"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
// Raw is the template as the API sent it.
Raw json.RawMessage `json:"-"`
}
Template is a template of the workspace, without its versions' content.
func (*Template) UnmarshalJSON ¶
UnmarshalJSON reads a template leniently and keeps it in Raw.
type TemplateListOptions ¶
type TemplateListOptions struct {
// Kind is pdf, image, docx or pptx; Engine jinja2, liquid or handlebars.
Kind string
Engine string
Tag string
// Q searches names and slugs.
Q string
Limit int
Cursor string
}
TemplateListOptions narrows TemplatesService.List and All.
type TemplateValidation ¶
type TemplateValidation struct {
// OK is false when at least one diagnostic is an error.
OK bool `json:"ok"`
// Template is the template and the version that was checked.
Template struct {
ID string `json:"id"`
Slug string `json:"slug"`
Version int `json:"version"`
} `json:"template"`
// Diagnostics are every finding, errors and warnings alike.
Diagnostics []Diagnostic `json:"diagnostics"`
// Raw is the answer as the API sent it.
Raw json.RawMessage `json:"-"`
}
TemplateValidation is what TemplatesService.Validate found.
func (*TemplateValidation) UnmarshalJSON ¶
func (v *TemplateValidation) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a validation leniently and keeps it in Raw.
type TemplatesService ¶
type TemplatesService struct {
// contains filtered or unexported fields
}
TemplatesService reads and checks the workspace's templates. Writing them (versions, publishing, channels) is the command line's and the app's; Client.Request reaches those calls.
func (*TemplatesService) All ¶
func (s *TemplatesService) All(ctx context.Context, opts TemplateListOptions) iter.Seq2[*Template, error]
All iterates over every template the options match, page after page; an error ends it as its last value.
func (*TemplatesService) List ¶
func (s *TemplatesService) List(ctx context.Context, opts TemplateListOptions) (*Page[Template], error)
List reads one page of templates.
func (*TemplatesService) Schema ¶
func (s *TemplatesService) Schema(ctx context.Context, idOrSlug, version string) (map[string]any, error)
Schema reads the JSON Schema of the template's data: stored, else inferred from the sample data. Of the published (else the latest) version, or of version: published, latest, a number or a channel name.
func (*TemplatesService) Validate ¶
func (s *TemplatesService) Validate(ctx context.Context, idOrSlug string, req ValidateTemplateRequest) (*TemplateValidation, error)
Validate checks a version with data without rendering: syntax, header and footer, missing partials, runtime errors and the data against the stored schema. Free. Without Data, the version's sample data is checked.
type ToImageRequest ¶
type ToImageRequest struct {
Source string `json:"source,omitempty"`
File *Upload `json:"-"`
// Pages are the pages to draw, such as 1, 1-3,5 or 2-; every page when empty.
Pages string `json:"pages,omitempty"`
// Format is png (the default) or jpg.
Format string `json:"format,omitempty"`
// DPI runs from 36 to 300, 150 when 0.
DPI int `json:"dpi,omitempty"`
// Quality is the JPEG quality, 1 to 100.
Quality int `json:"quality,omitempty"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
ToImageRequest draws pages as pictures: one page answers the picture, several a ZIP of them.
func (ToImageRequest) MarshalJSON ¶
func (r ToImageRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type UpdateWebhookRequest ¶
type UpdateWebhookRequest struct {
URL string `json:"url,omitempty"`
Events []string `json:"events,omitempty"`
Environments []string `json:"environments,omitempty"`
// Enabled switches the endpoint off, or on again, which resets its failures.
Enabled *bool `json:"enabled,omitempty"`
Description *string `json:"description,omitempty"`
// ClearDescription removes the description: it sends description as null.
ClearDescription bool `json:"-"`
Extra map[string]any `json:"-"`
}
UpdateWebhookRequest changes the fields it sets; the others stay.
func (UpdateWebhookRequest) MarshalJSON ¶
func (r UpdateWebhookRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members, and description as null for ClearDescription.
type Upload ¶
type Upload struct {
// Name is the file name, such as contract.pdf, which a tool's result is named after; in the
// file library it is the library name (brand/logo.png).
Name string
// ContentType is sent with the bytes; when empty, the extension of Name decides. The API reads
// the format from the bytes either way.
ContentType string
// Contents are the bytes.
Contents []byte
}
Upload is a file sent with a request: a PDF for the PDF tools, an office document to convert, an e-invoice XML to validate, an image or PDF for the file library. It is held in memory, so that a retry sends the same bytes again, and sent as multipart; the API keeps only what the library stores.
func UploadFromBytes ¶
UploadFromBytes is an upload of bytes you hold.
func UploadFromFile ¶
UploadFromFile reads a file into an upload named after it.
type Usage ¶
type Usage struct {
// Period is the month the period started in, YYYY-MM.
Period string `json:"period"`
// PeriodStart is the first day of the period, PeriodEnd the first day after it (YYYY-MM-DD).
PeriodStart string `json:"period_start"`
PeriodEnd string `json:"period_end"`
Included float64 `json:"included"`
Used float64 `json:"used"`
OverageUsed float64 `json:"overage_used"`
OverageBalance float64 `json:"overage_balance"`
// HardCapUnits is the units at which overage stops live renders; nil on a plan without
// overage and for an earlier period.
HardCapUnits *float64 `json:"hard_cap_units"`
Daily []struct {
Date string `json:"date"`
Units float64 `json:"units"`
Renders int `json:"renders"`
} `json:"daily"`
ByTemplate []struct {
Template string `json:"template"`
Units float64 `json:"units"`
} `json:"by_template"`
// Raw is the usage as the API sent it.
Raw json.RawMessage `json:"-"`
}
Usage is the units of a billing period, with a daily series and a breakdown per template.
func (*Usage) UnmarshalJSON ¶
UnmarshalJSON reads the usage leniently and keeps it in Raw.
type ValidateEinvoiceRequest ¶
type ValidateEinvoiceRequest struct {
RenderID string `json:"render_id,omitempty"`
File *Upload `json:"-"`
// Rules is auto, factur-x, xrechnung or en16931; the render's own when empty.
Rules string `json:"rules,omitempty"`
Extra map[string]any `json:"-"`
}
ValidateEinvoiceRequest names the e-invoice EinvoicesService.Validate judges: the RenderID of this workspace's own e-invoice, answered from the report it keeps, free; or a File, an XML Formfeed did not make (up to 4 MB, Starter plan and above), which takes one of the organisation's validations of the day.
func (ValidateEinvoiceRequest) MarshalJSON ¶
func (r ValidateEinvoiceRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type ValidateTemplateRequest ¶
type ValidateTemplateRequest struct {
// Version is published (the default), latest, a version number or a channel name.
Version string `json:"version,omitempty"`
// Data is the data to check; the version's sample data when nil.
Data map[string]any `json:"data,omitzero"`
Extra map[string]any `json:"-"`
}
ValidateTemplateRequest is what TemplatesService.Validate checks.
func (ValidateTemplateRequest) MarshalJSON ¶
func (r ValidateTemplateRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type WaitOption ¶
type WaitOption func(*waitConfig)
WaitOption configures RendersService.WaitFor and JobsService.WaitFor.
func WithPollInterval ¶
func WithPollInterval(d time.Duration) WaitOption
WithPollInterval sets the time between two reads: 1 second for a render, 2 for a job.
func WithWaitTimeout ¶
func WithWaitTimeout(d time.Duration) WaitOption
WithWaitTimeout sets how long WaitFor polls before it answers an *Error of code timeout: 120 seconds for a render, 600 for a job. The context's own deadline ends it earlier.
type WatermarkRequest ¶
type WatermarkRequest struct {
Source string `json:"source,omitempty"`
Text string `json:"text,omitempty"`
// Image is a PNG or JPEG of the file library, by id or name.
Image string `json:"image,omitempty"`
// Opacity runs from 0 to 1, 0.2 when nil.
Opacity *float64 `json:"opacity,omitempty"`
// Rotation is degrees clockwise as in CSS; when nil a text runs diagonally and an image stands
// upright.
Rotation *float64 `json:"rotation,omitempty"`
// Color is the hex colour of a text, grey when empty.
Color string `json:"color,omitempty"`
Filename string `json:"filename,omitempty"`
ExpiresIn int `json:"expires_in,omitempty"`
Access string `json:"access,omitempty"`
Meta map[string]any `json:"meta,omitzero"`
Storage any `json:"storage,omitempty"`
Extra map[string]any `json:"-"`
}
WatermarkRequest stamps a text or a library image on the pages; give Text or Image.
func (WatermarkRequest) MarshalJSON ¶
func (r WatermarkRequest) MarshalJSON() ([]byte, error)
MarshalJSON writes the request with its Extra members.
type Webhook ¶
type Webhook struct {
// Secret is the endpoint's signing secret, whsec_….
Secret string
// Tolerance is how old (or how far ahead) a delivery may be, in whole seconds;
// DefaultWebhookTolerance when 0.
Tolerance time.Duration
// Now is the clock; time.Now when nil.
Now func() time.Time
}
Webhook checks deliveries signed with an endpoint's secret: the header Webhook-Signature: t=<unix>,v1=<hex> is the HMAC-SHA256 of "<t>.<raw body>" with the secret, at most Tolerance either way from now, compared in constant time. Pass the body exactly as it arrived: the signature covers the bytes on the wire.
hook := formfeed.Webhook{Secret: os.Getenv("FORMFEED_WEBHOOK_SECRET")}
event, err := hook.Parse(r.Header.Get("Webhook-Signature"), body)
func (Webhook) Handler ¶
func (w Webhook) Handler(handle func(http.ResponseWriter, *http.Request, *WebhookEvent)) http.Handler
Handler is a receiver: it reads each delivery, verifies it, and hands the event to handle, with the request's body there to read again. A delivery whose signature does not match is answered 401 without reaching handle, which Formfeed retries; handle answers the rest, a 2xx within a few seconds for a delivery it took.
http.Handle("POST /webhooks/formfeed", hook.Handler(func(w http.ResponseWriter, r *http.Request, event *formfeed.WebhookEvent) {
if event.Type == "render.completed" { … }
w.WriteHeader(http.StatusNoContent)
}))
Example ¶
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")}
http.Handle("POST /webhooks/formfeed", hook.Handler(func(w http.ResponseWriter, r *http.Request, event *formfeed.WebhookEvent) {
if event.Type == "render.completed" {
render, err := event.Render()
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
log.Println("ready:", render.ID, render.DownloadURL)
}
w.WriteHeader(http.StatusNoContent)
}))
log.Fatal(http.ListenAndServe(":8080", nil))
}
Output:
type WebhookEndpoint ¶
type WebhookEndpoint struct {
// ID is the endpoint id, a UUID.
ID string `json:"id"`
URL string `json:"url"`
Events []string `json:"events"`
Environments []string `json:"environments"`
// Enabled is whether events are delivered; true when the answer leaves it out.
Enabled bool `json:"enabled"`
Description string `json:"description"`
ConsecutiveFailures int `json:"consecutive_failures"`
// Secret signs the deliveries (whsec_…); verify them with [Webhook].
Secret string `json:"secret"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
// Raw is the endpoint as the API sent it.
Raw json.RawMessage `json:"-"`
}
WebhookEndpoint is a registered webhook endpoint. Secret is only in the answer that created it.
func (*WebhookEndpoint) UnmarshalJSON ¶
func (w *WebhookEndpoint) UnmarshalJSON(data []byte) error
UnmarshalJSON reads an endpoint leniently and keeps it in Raw.
type WebhookEvent ¶
type WebhookEvent struct {
// ID is the event id, evt_…, which WebhooksService.Resend takes.
ID string `json:"id"`
// Type is render.completed, render.failed, job.completed, job.failed, quota.warning,
// quota.exceeded, storage.delivered, storage.failed or webhook.test, and takes new values.
Type string `json:"type"`
CreatedAt string `json:"created_at"`
WorkspaceID string `json:"workspace_id"`
Data json.RawMessage `json:"data"`
}
WebhookEvent is a verified delivery's event. Data is the render (render.*), the job (job.*), the usage (quota.*) or the delivery (storage.*) as the API writes them.
func ParseWebhook ¶
func ParseWebhook(secret, signatureHeader string, body []byte) (*WebhookEvent, error)
ParseWebhook verifies a delivery, as VerifyWebhook does, and reads its event.
func (*WebhookEvent) Job ¶
func (e *WebhookEvent) Job() (*Job, error)
Job reads Data as the job of a job.* event.
func (*WebhookEvent) Render ¶
func (e *WebhookEvent) Render() (*Render, error)
Render reads Data as the render of a render.* event.
type WebhookResend ¶
type WebhookResend struct {
DeliveryID string `json:"delivery_id"`
EventID string `json:"event_id"`
Event string `json:"event"`
EndpointID string `json:"endpoint_id"`
}
WebhookResend is the new delivery of WebhooksService.Resend.
type WebhookTest ¶
type WebhookTest struct {
// Queued is true once the test event is queued; the delivery log shows its outcome.
Queued bool `json:"queued"`
}
WebhookTest is the answer to WebhooksService.Test.
type WebhooksService ¶
type WebhooksService struct {
// contains filtered or unexported fields
}
WebhooksService manages the workspace's webhook endpoints. Needs webhook:manage. Verify a delivery with Webhook.
func (*WebhooksService) Create ¶
func (s *WebhooksService) Create(ctx context.Context, req CreateWebhookRequest) (*WebhookEndpoint, error)
Create registers an endpoint; the answer carries its Secret, this once.
func (*WebhooksService) Delete ¶
func (s *WebhooksService) Delete(ctx context.Context, id string) error
Delete removes an endpoint.
func (*WebhooksService) List ¶
func (s *WebhooksService) List(ctx context.Context) ([]WebhookEndpoint, error)
List reads the registered endpoints, without their secrets.
func (*WebhooksService) Resend ¶
func (s *WebhooksService) Resend(ctx context.Context, eventID, endpointID string) (*WebhookResend, error)
Resend sends a stored event (evt_…) again, as a new delivery to an endpoint.
func (*WebhooksService) Test ¶
func (s *WebhooksService) Test(ctx context.Context, id string) (*WebhookTest, error)
Test sends a test delivery to the endpoint.
func (*WebhooksService) Update ¶
func (s *WebhooksService) Update(ctx context.Context, id string, req UpdateWebhookRequest) (*WebhookEndpoint, error)
Update changes the fields the request sets; the others stay.