runconvert

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: 19 Imported by: 0

README

RunConvert SDK for Go

Convert files between 240+ formats (3,000+ conversions) with the RunConvert API: documents, images, video, audio, ebooks, archives, fonts and CAD. Go 1.21+, standard library only.

go get github.com/runconvert/runconvert-go
import runconvert "github.com/runconvert/runconvert-go"

rc := runconvert.New("") // reads RUNCONVERT_API_KEY

// One call: upload, convert, wait, download.
res, err := rc.Convert(ctx, "report.docx", runconvert.ConvertOptions{To: "pdf", OutDir: "out"})
fmt.Println(res.Saved) // [out/report.pdf]

Get an API key in Dashboard → API Keys on runconvert.com. Keep keys on the server.

Convert

// From a URL (imported by RunConvert, nothing to upload)
rc.Convert(ctx, "https://example.com/talk.mp4", runconvert.ConvertOptions{To: "mp3", Options: map[string]any{"audioBitrate": "192k"}})

// From an io.Reader: give a Filename (or From)
rc.Convert(ctx, reader, runconvert.ConvertOptions{To: "jpg", Filename: "photo.heic", OutDir: "out"})

// Time limit: use the context
ctx, cancel := context.WithTimeout(ctx, 10*time.Minute)
defer cancel()

Jobs with your own tasks

// Merge three PDFs into one
job, err := rc.Jobs.Create(ctx, runconvert.JobCreate{Tag: "merge", Tasks: map[string]runconvert.TaskDefinition{
	"a":      runconvert.ImportURL("https://example.com/cover.pdf"),
	"b":      runconvert.ImportURL("https://example.com/body.pdf"),
	"merge":  runconvert.ConvertTask("pdf", "pdf", []string{"a", "b"}, nil),
	"export": runconvert.ExportURL("merge"),
}})
job, err = rc.Jobs.Wait(ctx, job.ID, runconvert.WaitOptions{})
for _, f := range job.ExportedFiles() {
	rc.Files.Download(ctx, f.URL, "out", f.Filename)
}

// Upload your own file
job, err = rc.Jobs.Create(ctx, runconvert.JobCreate{Tasks: map[string]runconvert.TaskDefinition{
	"upload":  runconvert.ImportUpload(),
	"convert": runconvert.ConvertTask("png", "webp", "upload", map[string]any{"image_quality": 80}),
	"export":  runconvert.ExportURL("convert"),
}})
err = rc.Files.Upload(ctx, job.Task("upload").UploadURL, "image.png", "")
Method What it does
rc.Jobs.Create / Get / List / All / Wait / Cancel / Delete Jobs, with paging (List, All) and polling (Wait)
rc.Files.Upload(ctx, uploadURL, pathOrReader, name) / Download(ctx, url, dir, name) Transfers
rc.Operations.List(ctx, category) / ForInput(ctx, "mp4") / ForPair(ctx, "mp4", "mp3") Formats, targets, engines (no key needed)
rc.Me(ctx) Account, team and credit balance

Webhooks

http.HandleFunc("/webhooks/runconvert", func(w http.ResponseWriter, r *http.Request) {
	body, _ := io.ReadAll(r.Body)
	ev, err := runconvert.ConstructEvent(body, r.Header.Get("X-RunConvert-Signature"), os.Getenv("RUNCONVERT_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, "bad signature", http.StatusBadRequest)
		return
	}
	if ev.Event == "job.finished" {
		log.Println("done", ev.Job.ID)
	}
})

Errors

Error When
*runconvert.Error The API said no: Status, Code (e.g. BILLING_INSUFFICIENT_CREDITS), Message
*runconvert.JobFailedError The job ended in error; Task.Code, Task.Reason, Task.Message say why
runconvert.ErrWaitTimeout (wrapped) Wait ran past its Timeout

Network errors, 429 and 5xx are retried twice with backoff (WithMaxRetries). Creating a job is only retried when the request never reached the API, so a job is never created twice.

Development

go test ./...                                              # no network
RUNCONVERT_API_KEY=rc_live_… go test -run Live -v ./...    # real API, about 2 credits

License

MIT

Documentation

Overview

Package runconvert is the official Go SDK for the RunConvert API (v3): convert files between 240+ formats.

rc := runconvert.New("") // reads RUNCONVERT_API_KEY
res, err := rc.Convert(ctx, "report.docx", runconvert.ConvertOptions{To: "pdf", OutDir: "out"})

Index

Constants

View Source
const (
	StatusWaiting    = "waiting"
	StatusProcessing = "processing"
	StatusFinished   = "finished"
	StatusError      = "error"
)

Job statuses (tasks use the same).

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

DefaultBaseURL is the production API.

View Source
const Version = "0.1.0"

Version of this SDK.

Variables

View Source
var ErrWaitTimeout = errors.New("runconvert: timed out waiting for the job")

ErrWaitTimeout is returned (wrapped) when Wait gives up.

Functions

func VerifySignature

func VerifySignature(rawBody []byte, signature, secret string) bool

VerifySignature checks a delivery's X-RunConvert-Signature header ("sha256=" + hex HMAC-SHA256 of the raw body, keyed with the endpoint's secret). Pass the body as received.

Types

type Client

type Client struct {
	Jobs       *JobsService
	Operations *OperationsService
	Files      *FilesService
	// contains filtered or unexported fields
}

Client talks to the RunConvert API. Create one with New and reuse it.

func New

func New(apiKey string, opts ...Option) *Client

New creates a client. An empty apiKey reads RUNCONVERT_API_KEY.

func (*Client) Convert

func (c *Client) Convert(ctx context.Context, input any, o ConvertOptions) (*ConvertResult, error)

Convert converts one file in one call: upload (or import a URL), convert, wait, download. input is a local path, an http(s) URL, or an io.Reader (then set Filename or From). Use ctx for a time limit.

func (*Client) Me

func (c *Client) Me(ctx context.Context) (*Me, error)

Me returns the account, team and credit balance behind the API key.

type ConvertOptions

type ConvertOptions struct {
	To       string         // target format, e.g. "mp3" (required)
	From     string         // source format; read from the file name or URL when empty
	Options  map[string]any // engine options, e.g. {"audioBitrate": "192k"}
	OutDir   string         // save results here (created if needed); empty: don't download
	Filename string         // file name for an io.Reader input (also sets From)
	Tag      string
	OnUpdate func(*Job)
}

ConvertOptions for Convert.

type ConvertResult

type ConvertResult struct {
	Job   *Job
	Files []File   // the converted files, with temporary download links
	Saved []string // local paths, when OutDir was set
}

ConvertResult of Convert.

type Engine

type Engine struct {
	Name    string         `json:"name"`
	Credits int            `json:"credits"`
	Options []EngineOption `json:"options"`
}

Engine converts one pair.

type EngineOption

type EngineOption struct {
	Name            string            `json:"name"`
	Type            string            `json:"type"`
	Description     string            `json:"description"`
	SupportedValues []json.RawMessage `json:"supported_values"`
}

EngineOption is a setting a convert task accepts.

type Error

type Error struct {
	Status  int    // HTTP status, 0 when there was no response
	Code    string // API error code, may be empty
	Message string
	Body    []byte
}

Error is an API error: {"success": false, "error": {"code", "message"}}. Code is machine-readable (e.g. BILLING_INSUFFICIENT_CREDITS); new codes can appear.

func (*Error) Error

func (e *Error) Error() string

type File

type File struct {
	Filename  string `json:"filename"`
	URL       string `json:"url"` // temporary download link
	Size      int64  `json:"size,omitempty"`
	CreatedAt string `json:"created_at,omitempty"`
}

File is a result file.

type FilesService

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

FilesService uploads to import/direct/upload tasks and downloads results.

func (*FilesService) Download

func (s *FilesService) Download(ctx context.Context, fileURL, dir, filename string) (string, error)

Download saves a result file into dir (created if needed) and returns its path. filename "" uses the last part of the URL.

func (*FilesService) Upload

func (s *FilesService) Upload(ctx context.Context, uploadURL string, file any, filename string) error

Upload PUTs a file to a task's upload URL before its deadline. file is a local path or an io.Reader; filename (optional) keeps the file's name.

type InputFormat

type InputFormat struct {
	Format   string         `json:"format"`
	Category string         `json:"category"`
	Outputs  []OutputTarget `json:"outputs"`
}

InputFormat is a format and its targets.

type Job

type Job struct {
	ID          string         `json:"id"`
	Status      string         `json:"status"`
	Tag         *string        `json:"tag,omitempty"`
	Metadata    map[string]any `json:"metadata,omitempty"`
	CreditsUsed int            `json:"credits_used,omitempty"`
	CreditType  string         `json:"credit_type,omitempty"`
	CreatedAt   string         `json:"created_at,omitempty"`
	StartedAt   *string        `json:"started_at,omitempty"`
	EndedAt     *string        `json:"ended_at,omitempty"`
	ExpiresAt   *string        `json:"expires_at,omitempty"`
	UpdatedAt   string         `json:"updated_at,omitempty"`
	Tasks       []*Task        `json:"tasks,omitempty"`
}

Job holds named tasks.

func (*Job) ExportedFiles

func (j *Job) ExportedFiles() []File

ExportedFiles returns the files produced by the job's export/url tasks.

func (*Job) Task

func (j *Job) Task(name string) *Task

Task returns the task with this name, or nil.

type JobCreate

type JobCreate struct {
	Tasks    map[string]TaskDefinition `json:"tasks"`
	Tag      string                    `json:"tag,omitempty"`
	Metadata map[string]any            `json:"metadata,omitempty"`
}

JobCreate is the body of Jobs.Create.

type JobFailedError

type JobFailedError struct {
	Job  *Job
	Task *Task
}

JobFailedError: the job ended with status "error". Task is the first failed task.

func (*JobFailedError) Error

func (e *JobFailedError) Error() string

type JobsService

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

JobsService creates, reads, waits for and stops jobs.

func (*JobsService) All

func (s *JobsService) All(ctx context.Context, p ListParams, fn func(*Job) bool) error

All calls fn for every job, page by page; return false from fn to stop.

func (*JobsService) Cancel

func (s *JobsService) Cancel(ctx context.Context, id string) (*Job, error)

Cancel cancels pending tasks; credits for unfinished tasks are refunded.

func (*JobsService) Create

func (s *JobsService) Create(ctx context.Context, body JobCreate) (*Job, error)

Create creates a job. It comes back with its tasks (an upload task carries UploadURL).

func (*JobsService) Delete

func (s *JobsService) Delete(ctx context.Context, id string) error

Delete deletes a job.

func (*JobsService) Get

func (s *JobsService) Get(ctx context.Context, id string) (*Job, error)

Get returns a job with its tasks.

func (*JobsService) List

func (s *JobsService) List(ctx context.Context, p ListParams) ([]*Job, ListMeta, error)

List returns one page of jobs, newest first.

func (*JobsService) Wait

func (s *JobsService) Wait(ctx context.Context, id string, o WaitOptions) (*Job, error)

Wait polls until the job is finished or error (0.7s, slowing to 3s between polls). A failed job returns *JobFailedError unless NoErrorOnFail.

type ListMeta

type ListMeta struct {
	Page       int `json:"page"`
	PerPage    int `json:"per_page"`
	Total      int `json:"total"`
	TotalPages int `json:"total_pages"`
}

ListMeta is the paging info of a list.

type ListParams

type ListParams struct {
	Status       string
	Tag          string
	Page         int
	PerPage      int
	IncludeTasks bool
}

ListParams filters Jobs.List.

type Me

type Me struct {
	User struct {
		Email    string `json:"email"`
		FullName string `json:"full_name"`
	} `json:"user"`
	Team struct {
		Name string `json:"name"`
	} `json:"team"`
	APIKey *struct {
		Name string `json:"name"`
	} `json:"api_key"`
	Credits *struct {
		Mode           string `json:"mode"`
		DailyLimit     int64  `json:"daily_limit"`
		DailyRemaining int64  `json:"daily_remaining"`
		TotalRemaining int64  `json:"total_remaining"`
	} `json:"credits"`
}

Me is the account behind the key.

type OperationsCatalog

type OperationsCatalog struct {
	Categories []string      `json:"categories"`
	Formats    []InputFormat `json:"formats"`
}

OperationsCatalog lists every format.

type OperationsService

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

OperationsService lists formats, targets, engines and options. Public: no key needed.

func (*OperationsService) ForInput

func (s *OperationsService) ForInput(ctx context.Context, input string) (*InputFormat, error)

ForInput returns what one format converts to, with credit costs.

func (*OperationsService) ForPair

func (s *OperationsService) ForPair(ctx context.Context, input, output string) (*PairEngines, error)

ForPair returns the engines for input → output and the options a convert task accepts.

func (*OperationsService) List

func (s *OperationsService) List(ctx context.Context, category string) (*OperationsCatalog, error)

List returns every input format with its targets (category "" for all).

type Option

type Option func(*Client)

Option configures a Client.

func WithBaseURL

func WithBaseURL(u string) Option

WithBaseURL points the client at another API (tests, staging).

func WithHTTPClient

func WithHTTPClient(h *http.Client) Option

WithHTTPClient replaces the HTTP client used for API calls and transfers.

func WithMaxRetries

func WithMaxRetries(n int) Option

WithMaxRetries sets retries for network errors, 429 and 5xx (default 2).

func WithTimeout

func WithTimeout(d time.Duration) Option

WithTimeout sets the per-request timeout for API calls (default 60s). Uploads and downloads have none.

type OutputTarget

type OutputTarget struct {
	Format            string `json:"format"`
	Category          string `json:"category"`
	Engine            string `json:"engine"`
	Credits           int    `json:"credits"`
	BrowserCapable    bool   `json:"browser_capable"`
	BrowserMaxBytes   int64  `json:"browser_max_bytes"`
	BrowserMaxSeconds int    `json:"browser_max_seconds"`
}

OutputTarget is a format an input converts to.

type PairEngines

type PairEngines struct {
	Input   string   `json:"input"`
	Output  string   `json:"output"`
	Engines []Engine `json:"engines"`
}

PairEngines are the engines for input → output.

type Task

type Task struct {
	ID             string   `json:"id,omitempty"`
	JobID          string   `json:"job_id,omitempty"`
	Name           string   `json:"name"`
	Operation      string   `json:"operation"`
	Status         string   `json:"status"`
	Percent        int      `json:"percent,omitempty"`
	Message        string   `json:"message,omitempty"`
	Engine         string   `json:"engine,omitempty"`
	EngineVersion  string   `json:"engine_version,omitempty"`
	Credits        int      `json:"credits,omitempty"`
	Input          []string `json:"input,omitempty"`
	UploadURL      string   `json:"upload_url,omitempty"`
	UploadDeadline string   `json:"upload_deadline,omitempty"`
	Result         *struct {
		Files []File `json:"files"`
	} `json:"result,omitempty"`
	Code         string         `json:"code,omitempty"`
	Reason       string         `json:"reason,omitempty"`
	ReasonParams map[string]any `json:"reason_params,omitempty"`
	CreatedAt    string         `json:"created_at,omitempty"`
	StartedAt    *string        `json:"started_at,omitempty"`
	EndedAt      *string        `json:"ended_at,omitempty"`
	ExpiresAt    *string        `json:"expires_at,omitempty"`
}

Task is a step of a job. On error, Code is the category and Reason the exact, stable cause.

type TaskDefinition

type TaskDefinition map[string]any

TaskDefinition is one named task in a job: import/url, import/direct/upload, convert or export/url. Build them with ImportURL, ImportUpload, ConvertTask and ExportURL, or as a map.

func ConvertTask

func ConvertTask(inputFormat, outputFormat string, input any, options map[string]any) TaskDefinition

ConvertTask converts the output of input (a task name, or []string to merge/combine). options are engine settings from Operations.ForPair, e.g. {"audioBitrate": "192k"}.

func ExportURL

func ExportURL(input any) TaskDefinition

ExportURL makes temporary download links for input (a task name or []string).

func ImportURL

func ImportURL(sourceURL string) TaskDefinition

ImportURL imports a file from a public http(s) URL.

func ImportUpload

func ImportUpload() TaskDefinition

ImportUpload creates an upload task; the created task carries UploadURL (see Files.Upload).

type WaitOptions

type WaitOptions struct {
	Timeout       time.Duration // 0: no limit besides ctx
	OnUpdate      func(*Job)
	NoErrorOnFail bool // return a failed job instead of *JobFailedError
}

WaitOptions for Wait.

type WebhookEvent

type WebhookEvent struct {
	Event string `json:"event"` // job.finished, task.error, …
	Job   *Job   `json:"job,omitempty"`
	Task  *Task  `json:"task,omitempty"`
}

WebhookEvent is the JSON a webhook delivery carries.

func ConstructEvent

func ConstructEvent(rawBody []byte, signature, secret string) (*WebhookEvent, error)

ConstructEvent verifies the signature, then parses the event.

Jump to

Keyboard shortcuts

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