privconvert

package module
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

PrivConvert for Go

Official Go client for the PrivConvert API: file conversion for your app with zero data retention. Every file is processed in memory on our side and never written to disk.

  • No dependencies, standard library only (cloud storage support is a separate module)
  • Go 1.22+ (the cloud module needs Go 1.26+, like the cloud SDKs it uses)
  • Large files (above 90 MB) are uploaded in parts automatically
  • Async jobs, webhook signature verification and typed errors included

Go Reference

Install

go get github.com/toprivHQ/privconvert-go

Quick start

Create a key on your account page (new accounts can start a free trial of 25 conversions) and set it as an environment variable:

export PRIVCONVERT_API_KEY=pk_live_...
package main

import (
	"context"
	"fmt"
	"log"

	"github.com/toprivHQ/privconvert-go"
)

func main() {
	ctx := context.Background()
	pc, err := privconvert.New()
	if err != nil {
		log.Fatal(err)
	}
	res, err := pc.ConvertFile(ctx, "word-to-pdf", "contract.docx", nil)
	if err != nil {
		log.Fatal(err)
	}
	if err := res.Save("contract.pdf"); err != nil {
		log.Fatal(err)
	}
	if left, ok := res.CreditsRemaining(); ok {
		fmt.Println(left)
	}
}

Data you already have in memory goes in a File. Tool options go in Params:

res, err := pc.Convert(ctx, "compress-image", privconvert.File{Name: "photo.png", Data: data}, privconvert.Params{"quality": 70})

The tool id is the same slug as on the site. List them with pc.Tools(ctx, "") or pc.Tools(ctx, "document").

Many files at once

Up to 20 files in one request, returned as a ZIP. A batch costs one slot of your per-minute rate limit.

zip, err := pc.ConvertBatch(ctx, "png-to-jpg", files, nil)
if err != nil {
	log.Fatal(err)
}
zip.Save("converted.zip")
if zip.Partial() {
	fmt.Println(zip.FailedCount(), "files were skipped, see PRIVCONVERT-ERRORS.txt in the ZIP")
}

Files in cloud storage

Convert a file in Amazon S3, Google Cloud Storage or Azure Blob Storage and write the result back. The cloud libraries live in a separate module, so the main one stays free of dependencies:

go get github.com/toprivHQ/privconvert-go/cloud
import "github.com/toprivHQ/privconvert-go/cloud"

store := cloud.New(cloud.Options{})
defer store.Close()

pc.ConvertStorage(ctx, store, "word-to-pdf", "s3://my-bucket/input.docx", "s3://my-bucket/output.pdf", nil)
pc.ConvertStorage(ctx, store, "word-to-pdf", "gs://my-bucket/input.docx", "gs://my-bucket/output.pdf", nil)
pc.ConvertStorage(ctx, store, "word-to-pdf", "az://myaccount/my-container/input.docx", "az://myaccount/my-container/output.pdf", nil)

The cloud is picked from the address. Azure also accepts the blob URL from the portal (https://myaccount.blob.core.windows.net/my-container/input.docx). Source and destination can be in different clouds.

The file moves between your storage and PrivConvert from wherever this code runs, using your own credentials. Your credentials are never sent to PrivConvert, and we never get access to your storage. Run it in the same region as the bucket and the transfer is fast and cheap.

Credentials. Each cloud's standard sign-in is used: for S3 the AWS default chain (environment, shared config or IAM role), for Google Application Default Credentials, for Azure AZURE_STORAGE_CONNECTION_STRING or DefaultAzureCredential (managed identity, environment, Azure CLI). Clients are created on first use, so only the clouds you touch need credentials. To control it yourself, pass S3Client, GCSClient or AzureClient in cloud.Options.

Backblaze B2, Cloudflare R2 and other S3-compatible storage. Use an s3:// address and an S3 client pointed at the provider:

b2 := s3.New(s3.Options{
	Region:       "us-east-005",
	BaseEndpoint: aws.String("https://s3.us-east-005.backblazeb2.com"),
	Credentials:  credentials.NewStaticCredentialsProvider(os.Getenv("B2_KEY_ID"), os.Getenv("B2_APP_KEY"), ""),
})
store := cloud.New(cloud.Options{S3Client: b2})

Options.

store := cloud.New(cloud.Options{
	// adjust the upload of the converted file
	S3PutObject: func(in *s3.PutObjectInput) { in.ServerSideEncryption = s3types.ServerSideEncryptionAwsKms },
})
pc.ConvertStorage(ctx, store, "word-to-pdf", "gs://in-bucket/contract.docx", "s3://out-bucket/contract.pdf",
	&privconvert.StorageOptions{
		NoOverwrite: true, // leave an existing file alone, before any credit is spent
	})

GCSWriter and AzureUpload do the same for Google and Azure. cloud.Storage implements the small privconvert.Storage interface, so you can also plug in your own.

Storage problems match privconvert.ErrStorage, with the provider's code in Code (for example NoSuchKey, NotFound, BlobNotFound or AccessDenied).

Async jobs

job, err := pc.SubmitJob(ctx, "pptx-to-pdf", file, nil)
// job.Key is returned once. Keep it if you need to download later or verify webhooks.
res, err := pc.Wait(ctx, job, nil) // polls, downloads, then deletes the stored result

With a webhook instead of polling:

job, err := pc.SubmitJob(ctx, "pptx-to-pdf", file, &privconvert.JobOptions{WebhookURL: "https://example.com/hooks/privconvert"})
saveSomewhere(job.ID, job.Key)
// later, when the webhook arrives:
res, err := pc.DownloadJob(ctx, job)

Verifying webhooks

Pass the raw request body, not decoded JSON:

func hook(w http.ResponseWriter, r *http.Request) {
	raw, _ := io.ReadAll(http.MaxBytesReader(w, r.Body, 1<<20))
	jobKey := loadJobKey(raw)
	if err := privconvert.VerifyWebhook(jobKey, r.Header.Get("X-PrivConvert-Signature"), raw); err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	// ...
}

Deliveries older than 5 minutes are rejected as replays (VerifyWebhookAt to change it).

Errors

Every error is a *privconvert.Error with Status, Code, Message and RetryAfter. Check the kind with errors.Is:

Value When
ErrAuthentication Missing or invalid key (401)
ErrBadRequest Bad request or unreadable input (400)
ErrFileTooLarge Above your plan's size limit (413)
ErrUnsupportedType Wrong input type for the tool (415)
ErrConversionFailed File read but could not be converted (422)
ErrRateLimit Per-minute rate or monthly quota exceeded (429)
ErrConcurrencyLimit Too many conversions at once (429, also matches ErrRateLimit)
ErrServer Problem on our side (5xx)
ErrStorage Reading from or writing to your cloud storage failed
var pe *privconvert.Error
if errors.As(err, &pe) && errors.Is(err, privconvert.ErrRateLimit) {
	log.Printf("slow down, retry in %s", pe.RetryAfter)
}

Short 429, 502, 503 and 504 responses are retried automatically (WithMaxRetries, default 2), honouring Retry-After. A long Retry-After, which means the monthly quota is used up, returns at once instead of sleeping.

Usage and limits

me, err := pc.Me(ctx)
// map[tier:growth quota:25000 used:1234 remaining:23766 rpm:120 ...]

Security notes

  • The key is read from PRIVCONVERT_API_KEY or passed with WithAPIKey, and never appears when the client or a job is printed.
  • Requests go over HTTPS only. A plain http:// base URL is refused.
  • This package writes nothing to disk except where you call Result.Save.
  • ConvertStorage keeps the file in memory between your storage and the API. Your cloud credentials stay with you.

MIT License

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

View Source
const DefaultBaseURL = "https://privconvert.com/api"

DefaultBaseURL is the production API.

View Source
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.

View Source
const Version = "0.1.0"

Version of this package, sent in the User-Agent header.

Variables

View Source
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

func VerifyWebhook(jobKey, signature string, rawBody []byte) error

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.

func VerifyWebhookAt

func VerifyWebhookAt(jobKey, signature string, rawBody []byte, now time.Time, tolerance time.Duration) error

VerifyWebhookAt is VerifyWebhook with an explicit clock and tolerance.

Types

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client talks to the PrivConvert API. It is safe for concurrent use.

func New

func New(opts ...Option) (*Client, error)

New creates a client.

func (*Client) Convert

func (c *Client) Convert(ctx context.Context, tool string, f File, params Params) (*Result, error)

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) DeleteJob

func (c *Client) DeleteJob(ctx context.Context, jobID string) error

DeleteJob wipes a job and its stored result.

func (*Client) DownloadJob

func (c *Client) DownloadJob(ctx context.Context, job *Job) (*Result, error)

DownloadJob downloads the result of a finished job.

func (*Client) GetJob

func (c *Client) GetJob(ctx context.Context, jobID string) (*JobStatus, error)

GetJob returns the current state of a job.

func (*Client) GoString

func (c *Client) GoString() string

func (*Client) Me

func (c *Client) Me(ctx context.Context) (map[string]any, error)

Me returns your plan, monthly quota and current usage.

func (*Client) String

func (c *Client) String() string

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.

func (*Client) Tools

func (c *Client) Tools(ctx context.Context, category string) ([]map[string]any, error)

Tools returns the public catalog of every tool, optionally filtered by category.

func (*Client) Wait

func (c *Client) Wait(ctx context.Context, job *Job, opts *WaitOptions) (*Result, error)

Wait polls until the job finishes, then downloads the result.

If the job failed, it returns the same error a synchronous call would have.

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

func StorageError(msg, code string) *Error

StorageError builds the error a Storage implementation returns, so callers can match it with errors.Is(err, ErrStorage).

func (*Error) Error

func (e *Error) Error() string

func (*Error) Is

func (e *Error) Is(target error) bool

func (*Error) Unwrap

func (e *Error) Unwrap() error

type File

type File struct {
	Name string
	Data []byte
}

File is a file held in memory, ready to upload.

func ReadFile

func ReadFile(path string) (File, error)

ReadFile reads a file from disk into a File named after its base name.

func (File) GoString

func (f File) GoString() string

func (File) String

func (f File) String() string

type Job

type Job struct {
	ID     string
	Key    string
	Status string
}

Job is a submitted async job. Key is returned exactly once: store it.

func (Job) GoString

func (j Job) GoString() string

func (Job) String

func (j Job) String() string

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

type JobStatus struct {
	ID     string
	Status string
	Raw    map[string]any
}

JobStatus is the state of a job as reported by the API.

func (*JobStatus) Done

func (s *JobStatus) Done() bool

Done is true once the job has finished or failed.

func (*JobStatus) ErrorInfo

func (s *JobStatus) ErrorInfo() map[string]any

ErrorInfo is the job's error object, when it failed.

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

func ParseLocation(s string) (Location, error)

ParseLocation parses s3://bucket/key, gs://bucket/key, az://account/container/blob or https://account.blob.core.windows.net/container/blob.

func (Location) String

func (l Location) String() string

type Option

type Option func(*Client) error

Option configures a Client.

func WithAPIKey

func WithAPIKey(key string) Option

WithAPIKey sets the key. Without it, PRIVCONVERT_API_KEY is used.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL points the client at another server. It must use https, except for localhost.

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient uses your own http.Client, for proxies or custom transports.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets how often short 429, 502, 503 and 504 responses are retried (2).

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout of the default HTTP client (300s).

type Params

type Params map[string]any

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

type Result struct {
	Content     []byte
	Filename    string
	ContentType string
	Header      http.Header
}

Result is a converted file, held in memory.

func (*Result) ConvertedCount

func (r *Result) ConvertedCount() (int, bool)

ConvertedCount is the number of files a batch converted, when reported.

func (*Result) CreditsRemaining

func (r *Result) CreditsRemaining() (int, bool)

CreditsRemaining is the balance after this conversion, when the API reported it.

func (*Result) FailedCount

func (r *Result) FailedCount() int

FailedCount is the number of files a batch skipped.

func (*Result) Partial

func (r *Result) Partial() bool

Partial is true when a batch succeeded for only some of its files.

func (*Result) SanitizeReport

func (r *Result) SanitizeReport() map[string]any

SanitizeReport is the parsed X-Sanitize-Report header, or nil.

func (*Result) Save

func (r *Result) Save(path string) error

Save writes the result to path with mode 0644.

func (*Result) String

func (r *Result) String() string

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.

Directories

Path Synopsis
cloud module

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL