Documentation
¶
Overview ¶
Package privconvert is the official Go client for the PrivConvert file conversion API. Every file is processed in memory on our side and never written to disk.
pc, err := privconvert.New() // reads PRIVCONVERT_API_KEY
res, err := pc.ConvertFile(ctx, "word-to-pdf", "contract.docx", nil)
err = res.Save("contract.pdf")
Converting files in Amazon S3, Google Cloud Storage or Azure Blob Storage is in the separate module github.com/toprivHQ/privconvert-go/cloud, so this one stays free of dependencies.
Index ¶
- Constants
- Variables
- func VerifyWebhook(jobKey, signature string, rawBody []byte) error
- func VerifyWebhookAt(jobKey, signature string, rawBody []byte, now time.Time, ...) error
- type Client
- func (c *Client) Convert(ctx context.Context, tool string, f File, params Params) (*Result, error)
- func (c *Client) ConvertBatch(ctx context.Context, tool string, files []File, params Params) (*Result, error)
- func (c *Client) ConvertFile(ctx context.Context, tool, path string, params Params) (*Result, error)
- func (c *Client) ConvertStorage(ctx context.Context, store Storage, tool, source, destination string, ...) (*Result, error)
- func (c *Client) DeleteJob(ctx context.Context, jobID string) error
- func (c *Client) DownloadJob(ctx context.Context, job *Job) (*Result, error)
- func (c *Client) GetJob(ctx context.Context, jobID string) (*JobStatus, error)
- func (c *Client) GoString() string
- func (c *Client) Me(ctx context.Context) (map[string]any, error)
- func (c *Client) String() string
- func (c *Client) SubmitJob(ctx context.Context, tool string, f File, opts *JobOptions) (*Job, error)
- func (c *Client) Tools(ctx context.Context, category string) ([]map[string]any, error)
- func (c *Client) Wait(ctx context.Context, job *Job, opts *WaitOptions) (*Result, error)
- type Error
- type File
- type Job
- type JobOptions
- type JobStatus
- type Location
- type Option
- type Params
- type Result
- type Storage
- type StorageOptions
- type WaitOptions
Constants ¶
const DefaultBaseURL = "https://privconvert.com/api"
DefaultBaseURL is the production API.
const MaxObjectBytes = 500 << 20
MaxObjectBytes is the largest file any plan accepts. Storage implementations check it before reading so a wrong key cannot pull gigabytes into memory.
const Version = "0.1.0"
Version of this package, sent in the User-Agent header.
Variables ¶
var ( ErrAuthentication = errors.New("privconvert: missing, invalid or revoked API key") // 401 ErrBadRequest = errors.New("privconvert: bad request") // 400 ErrFileTooLarge = errors.New("privconvert: file is above your plan's size limit") // 413 ErrUnsupportedType = errors.New("privconvert: input file type is not valid for this tool") // 415 ErrConversionFailed = errors.New("privconvert: the file was read but could not be converted") // 422 ErrRateLimit = errors.New("privconvert: per-minute rate or monthly quota exceeded") // 429 ErrConcurrencyLimit = errors.New("privconvert: too many conversions running at once") // 429, also matches ErrRateLimit ErrServer = errors.New("privconvert: server error") // 5xx, safe to retry ErrJobNotFound = errors.New("privconvert: job not found") // 404 for a job ErrJobExpired = errors.New("privconvert: job result passed its retention window") // 410 ErrStorage = errors.New("privconvert: reading from or writing to cloud storage failed") // see Error.Code ErrWebhook = errors.New("privconvert: webhook signature verification failed") )
Kinds of error. Test for them with errors.Is:
if errors.Is(err, privconvert.ErrRateLimit) { ... }
Functions ¶
func VerifyWebhook ¶
VerifyWebhook checks an X-PrivConvert-Signature header against the raw request body. It returns nil for an authentic delivery, or an error that matches ErrWebhook.
rawBody must be the exact bytes received, not re-encoded JSON. jobKey is the one-time key returned when the job was submitted. Deliveries older than five minutes are rejected as replays.
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client talks to the PrivConvert API. It is safe for concurrent use.
func (*Client) Convert ¶
Convert converts one file. Files above 90 MB are uploaded in parts automatically.
func (*Client) ConvertBatch ¶
func (c *Client) ConvertBatch(ctx context.Context, tool string, files []File, params Params) (*Result, error)
ConvertBatch runs one tool over up to 20 files; the result is a ZIP.
Check FailedCount / Partial: a batch where some files failed still succeeds with the files that converted.
func (*Client) ConvertFile ¶
func (c *Client) ConvertFile(ctx context.Context, tool, path string, params Params) (*Result, error)
ConvertFile reads path and converts it.
func (*Client) ConvertStorage ¶
func (c *Client) ConvertStorage(ctx context.Context, store Storage, tool, source, destination string, opts *StorageOptions) (*Result, error)
ConvertStorage converts a file in cloud storage and writes the result back to storage.
Source and destination may be in different clouds. The file moves between your storage and PrivConvert from wherever this code runs, using your own credentials through store. Your credentials are never sent to PrivConvert.
func (*Client) DownloadJob ¶
DownloadJob downloads the result of a finished job.
func (*Client) SubmitJob ¶
func (c *Client) SubmitJob(ctx context.Context, tool string, f File, opts *JobOptions) (*Job, error)
SubmitJob submits an async job. It returns at once with the job id and one-time key.
type Error ¶
type Error struct {
// Kind is one of the Err* values, or nil for a client-side problem such
// as an invalid argument.
Kind error
// Status is the HTTP status, or 0 when the error did not come from the API.
Status int
// Code is the API's error code (for example "rate_limited"), or for
// storage errors the provider's code (for example "NoSuchKey",
// "AccessDenied", "BlobNotFound" or "DestinationExists").
Code string
Message string
// RetryAfter is the server's Retry-After, when it sent one.
RetryAfter time.Duration
}
Error is the error type returned by this package. Use errors.As to read the details, and errors.Is with the Err* values to check the kind.
func StorageError ¶
StorageError builds the error a Storage implementation returns, so callers can match it with errors.Is(err, ErrStorage).
type File ¶
File is a file held in memory, ready to upload.
type JobOptions ¶
type JobOptions struct {
Params Params
// WebhookURL receives a signed POST when the job finishes. Must be https.
WebhookURL string
}
JobOptions are the optional settings of SubmitJob.
type JobStatus ¶
JobStatus is the state of a job as reported by the API.
type Location ¶
type Location struct {
Provider string // "s3", "gcs" or "azure"
Bucket string // S3 / GCS bucket, or Azure container
Key string
Account string // Azure storage account
}
Location is a single file in cloud storage.
func ParseLocation ¶
ParseLocation parses s3://bucket/key, gs://bucket/key, az://account/container/blob or https://account.blob.core.windows.net/container/blob.
type Option ¶
Option configures a Client.
func WithAPIKey ¶
WithAPIKey sets the key. Without it, PRIVCONVERT_API_KEY is used.
func WithBaseURL ¶
WithBaseURL points the client at another server. It must use https, except for localhost.
func WithHTTPClient ¶
WithHTTPClient uses your own http.Client, for proxies or custom transports.
func WithMaxRetries ¶
WithMaxRetries sets how often short 429, 502, 503 and 504 responses are retried (2).
func WithTimeout ¶
WithTimeout sets the per-request timeout of the default HTTP client (300s).
type Params ¶
Params are tool options sent as form fields, e.g. Params{"quality": 80}. Booleans are sent as "true"/"false"; slices and maps as JSON; nil values are skipped.
type Result ¶
Result is a converted file, held in memory.
func (*Result) ConvertedCount ¶
ConvertedCount is the number of files a batch converted, when reported.
func (*Result) CreditsRemaining ¶
CreditsRemaining is the balance after this conversion, when the API reported it.
func (*Result) FailedCount ¶
FailedCount is the number of files a batch skipped.
func (*Result) SanitizeReport ¶
SanitizeReport is the parsed X-Sanitize-Report header, or nil.
type Storage ¶
type Storage interface {
Exists(ctx context.Context, loc Location) (bool, error)
// Read returns the whole object, refusing objects above MaxObjectBytes.
Read(ctx context.Context, loc Location) ([]byte, error)
// Write stores data. With overwrite false it must not replace an existing
// object, and returns an error with Code "DestinationExists" or the
// provider's precondition code instead.
Write(ctx context.Context, loc Location, data []byte, contentType string, overwrite bool) error
}
Storage reads and writes single files in cloud storage. The module github.com/toprivHQ/privconvert-go/cloud provides one for Amazon S3 (and S3-compatible services), Google Cloud Storage and Azure Blob Storage.
Errors should be built with StorageError so callers can match ErrStorage.
type StorageOptions ¶
type StorageOptions struct {
Params Params
// NoOverwrite leaves an existing destination untouched and fails before
// any credit is spent.
NoOverwrite bool
}
StorageOptions are the optional settings of ConvertStorage.
type WaitOptions ¶
type WaitOptions struct {
// PollInterval is the first wait between polls (2s); it grows up to 10s.
PollInterval time.Duration
// Timeout applies when ctx has no deadline (30 minutes).
Timeout time.Duration
// KeepResult leaves the stored result on the server after download
// instead of deleting it right away.
KeepResult bool
}
WaitOptions are the optional settings of Wait.