Go Client

The packages go.xchunk.org/vela/client and go.xchunk.org/vela/api are public and stable within API v1. They are what the CLI itself uses, so anything the CLI can do, your Go program can do — with typed errors, retries and safe redirect handling built in.

Installation

go get go.xchunk.org/vela@latest
import (
	"go.xchunk.org/vela/api"
	"go.xchunk.org/vela/client"
)

The client depends only on the standard library and the api package — no AWS SDK, no CLI code.

Creating a client

c, err := client.New("https://store.example.com", os.Getenv("VELA_KEY"),
	client.WithUserAgent("release-bot/1.0"),
	client.WithHTTPClient(&http.Client{Timeout: 10 * time.Minute}),
)
if err != nil {
	log.Fatal(err) // invalid URL
}

info, err := c.CheckServer(ctx) // fails with client.ErrIncompatibleAPI on a different major version
if err != nil {
	log.Fatal(err)
}
fmt.Println(info.Key.Name, info.Key.Scope, info.Limits.MaxUploadBytes)

A Client is safe for concurrent use. Options:

OptionEffect
WithHTTPClient(*http.Client)Custom transport, proxies, TLS or timeouts. The client is copied, and redirect credential stripping is enforced even with your own CheckRedirect.
WithUserAgent(string)User-Agent header (default vela-go-client).
WithRetries(int)Retries after the first attempt for idempotent requests (default client.DefaultRetries = 2, i.e. three attempts).
WithBackoff(func(attempt int) time.Duration)Custom delay before retry n (1-based).
WithTrace(io.Writer)One line per HTTP exchange; the key is never written.

Uploading

f, err := os.Open("report.pdf")
if err != nil {
	return err
}
defer f.Close()
st, _ := f.Stat()

title := "Q3 report"
obj, created, err := c.Upload(ctx, "docs/q3/report.pdf", f, client.UploadOptions{
	Size:        st.Size(),     // -1 for unknown length (chunked)
	ContentType: "application/pdf",
	Visibility:  api.Public,
	Title:       &title,
	Tags:        []string{"finance", "q3"},
	Disposition: api.Inline,
	SHA256:      hexDigest,     // optional: server rejects a mismatch
	CreateOnly:  true,          // If-None-Match: *, safe to retry
})
switch {
case api.IsCode(err, api.CodeAlreadyExists):
	// exists already; overwrite with IfRevision or without CreateOnly
case err != nil:
	return err
}
if obj.URL != nil { // nil for private objects
	fmt.Println(created, *obj.URL)
}

Unset fields keep the current value when overwriting and take server defaults when creating. Tags replaces the list when non-nil; ClearExpiry removes an existing expiry; IfRevision only overwrites that revision. Conditional uploads (CreateOnly or IfRevision) are idempotent and therefore retried; unconditional overwrites are not.

Small files from memory

obj, err := c.Create(ctx, api.CreateObjectRequest{
	Path:       "notes/todo.md",
	Content:    "# Todo\n",
	Visibility: api.Private,
})

Create never overwrites and is not retried automatically. Use Encoding: api.EncodingBase64 for binary content.

Downloading

rc, info, err := c.Download(ctx, "docs/q3/report.pdf")
if err != nil {
	return err
}
defer rc.Close()

h := sha256.New()
n, err := io.Copy(io.MultiWriter(out, h), rc)
if err == nil && info.SHA256 != "" && hex.EncodeToString(h.Sum(nil)) != info.SHA256 {
	return errors.New("checksum mismatch")
}

DownloadInfo carries ContentType, Size (−1 if unknown) and SHA256 parsed from the ETag.

Listing and metadata

// one page
page, err := c.List(ctx, client.ListOptions{Prefix: "docs/", Limit: 100})

// everything below a prefix, following cursors
all, err := c.ListAll(ctx, client.ListOptions{
	Prefix:     "docs/",
	Recursive:  true,
	Visibility: []api.Visibility{api.Private},
})
for _, o := range all.Objects {
	fmt.Println(o.Path, o.Size)
}

// by tag: "q1", or both "math" and "draft"
tags, err := api.ParseTagFilter([]string{"q1", "math,draft"})
tagged, err := c.ListAll(ctx, client.ListOptions{Recursive: true, Tags: tags})

// broken symlinks below sorted/
broken, err := c.ListAll(ctx, client.ListOptions{Prefix: "sorted/", Recursive: true, Broken: true})

obj, err := c.Stat(ctx, "docs/q3/report.pdf")

// JSON Merge Patch with optimistic locking
obj, err = c.Patch(ctx, obj.Path, api.ObjectPatch{
	Title:     api.Some("Q3 report (final)"),
	ExpiresAt: api.Null[time.Time](), // remove the expiry
}, obj.Revision)
if api.IsCode(err, api.CodePreconditionFailed) {
	// someone changed it in between; re-read and retry
}

api.Some(v) sets a field, api.Null[T]() resets it, and an unset field is left alone.

ListOptions also takes Kind (api.KindFile or api.KindSymlink), Broken and Target (symlinks pointing at a path). Tags is sent as the tag parameter and applied to the returned objects, so a server that predates tag filters cannot widen the result; TrashOptions.Tags works the same way for trash entries.

Moving and deleting

res, err := c.Move(ctx, api.MoveRequest{
	From: "docs/2025/", To: "archive/2025/", Recursive: true,
})
fmt.Println(res.Moved, res.PoliciesMoved)

del, err := c.Delete(ctx, "drafts/", client.DeleteOptions{Recursive: true})
fmt.Println(del.Deleted, del.TrashIDs)

_, err = c.Delete(ctx, "secret.pdf", client.DeleteOptions{Purge: true}) // admin

del.SymlinksAffected reports how many symlinks the deletion left broken.

obj, created, err := c.CreateSymlink(ctx, api.CreateSymlinkRequest{
	Source: "originals/2026/lisbon.jpg",
	Path:   "sorted/travel/lisbon.jpg",
})
if api.IsCode(err, api.CodeAlreadyExists) {
	// pass Overwrite: true to retarget it in place
}
fmt.Println(obj.Kind, obj.Target.Path, created)

tree, err := c.CreateSymlinkTree(ctx, api.CreateSymlinkRequest{
	Source: "originals/2026/", Path: "sorted/2026/",
})
fmt.Println(tree.Created, tree.Replaced, tree.Skipped)

info, err := c.Info(ctx)
if !info.Features.Symlinks {
	// velad older than 0.4
}

CreateSymlink reports whether a new symlink was created (false after a retarget). Optional fields of CreateSymlinkRequest are pointers: nil keeps the default. Uploading to a symlink's path fails with api.CodeIsSymlink.

Trash

entries, err := c.ListAllTrash(ctx, client.TrashOptions{Path: "docs/welcome.txt"})
if err == nil && len(entries) > 0 {
	obj, err := c.Restore(ctx, entries[0].ID, api.RestoreRequest{Path: "docs/welcome-restored.txt"})
	_ = obj
}
res, err := c.PurgeTrash(ctx, "30d") // admin; "" empties the trash
link, err := c.CreateLink(ctx, api.CreateLinkRequest{
	Path: "private/report.md",
	TTL:  "2h",
	Note: "for the reviewer",
})
fmt.Println(*link.URL, link.ExpiresAt)

list, err := c.ListLinks(ctx, client.LinkListOptions{Path: "private/report.md", IncludeExpired: true})
err = c.RevokeLink(ctx, link.ID)

Directory policies

eff, err := c.ShowDir(ctx, "docs/")
fmt.Println(eff.Effective.Index, eff.ListedInParent)

_, err = c.PatchDir(ctx, "docs/raw/", api.DirPolicyPatch{
	Index: api.Some(api.IndexOff),
}, client.DirWriteOptions{})

_, err = c.PutDir(ctx, "event-2026/", api.DirPolicyRequest{
	Index: api.IndexOn, Hidden: true, Title: "Event 2026",
}, client.DirWriteOptions{CreateOnly: true})

rules, err := c.ListAllDirPolicies(ctx, client.DirListOptions{Orphaned: true})
err = c.DeleteDir(ctx, "docs/raw/", client.DirWriteOptions{})

Errors

API failures are returned as *api.Error with the server's code, message, details and request ID. Transport failures are *client.NetworkError.

_, err := c.Stat(ctx, "missing.txt")

var ae *api.Error
var ne *client.NetworkError
switch {
case api.IsCode(err, api.CodeNotFound):
	// 404
case errors.As(err, &ae):
	log.Printf("%s (%d): %s [request %s]", ae.Code, ae.Status(), ae.Message, ae.RequestID)
case errors.As(err, &ne):
	log.Printf("server unreachable: %v", errors.Unwrap(ne))
case errors.Is(err, client.ErrIncompatibleAPI):
	log.Print("server speaks a different API major version")
}

Network error messages never include raw URLs (which could be presigned), but the underlying cause is available through errors.Unwrap.

Behavior worth knowing

  • Retries: idempotent requests — reads, deletes, conditional uploads — are retried on network errors, 429 and 5xx with jittered exponential backoff. Create, Move, CreateSymlink, CreateSymlinkTree, CreateLink and Restore are never retried.
  • Redirects: Authorization and Referer are stripped on every redirect, so keys never reach an R2 presigned URL or any other host.
  • Paths: a leading slash is ignored; segments are escaped for you.
  • Contexts: every method takes a context.Context; cancel it to abort an upload or download.

Full API documentation is available with go doc go.xchunk.org/vela/client and on pkg.go.dev.