Collaborate SDK
Create workspaces, manage members and folders, and upload or download protected files with the most current SDKs available.
Collaborate provides workspace lifecycle and membership management, plus workspace-scoped file and folder operations.
Collaborate is a Virtru SaaS surface — NewClient requires an SDK connected to a
Virtru SaaS endpoint and returns ErrSaaSOnly otherwise. For
local development, WithLocalEndpoint supports a non-SaaS SDK whose
platform endpoint resolves exclusively to loopback addresses.
Use Files.Upload for content that the SDK should encrypt. This method owns the
complete upload flow.
Use Download a stored TDF to stream a stored TDF without
decrypting it.
Setup
The examples in this section use the Go programming language. References are also available for the REST API, Go SDK, TypeScript SDK, and CLI.
import (
"context"
virtru "go.pkg.virtru.com/virtru-sdk-go"
"go.pkg.virtru.com/virtru-sdk-go/collaborate"
)
ctx := context.Background()
// The default endpoint is the Virtru SaaS production endpoint, which Collaborate
// requires. Pass WithPlatformEndpoint only to target another Virtru SaaS
// environment (e.g. staging).
sdk, err := virtru.New(
virtru.WithClientCredentials(clientID, clientSecret, scopes),
)
if err != nil {
log.Fatal(err)
}
defer sdk.Close()
collaborateClient, err := collaborate.NewClient(ctx, sdk)
if err != nil {
log.Fatal(err)
}
Recommended path
For the common path, create or select a workspace and call
Files.Upload with
an io.ReadSeeker. The method encrypts and uploads the content in one call. It
does not stage either the source content or encrypted TDF on disk.
If the SDK cannot confirm that the
upload completed, it returns an *UploadError. Check the file's
status before retrying. If it is still PENDING, there is no finalize or resume
operation; retrying registers and uploads a new file.
Need generated protobuf requests/results or an RPC without a curated method? See generated service access for routing, availability, setup, and error differences. Raw calls do not provide Collaborate's scoped checks or upload/download workflows.
File transfer behavior
Files.Upload and
Download a stored TDF are the supported ways to
transfer files.
Files.Upload measures plaintext bytes, encrypts the source to a TDF, and
uploads the ciphertext in multipart parts. DownloadTDF writes raw TDF bytes only. It does not decrypt the
file or evaluate its policy and obligations. Decrypt or render the TDF after
download with the workflow appropriate for the caller.
Uploads use multipart transfer with 28 MiB parts and concurrency 2 by default.
WithUploadConfig changes those values while keeping upload memory bounded.
OnBytesRead measures bytes read from the input; OnPartOutcome reports each
multipart part's final storage result after retries.
DownloadTDF streams the TDF to the caller's io.Writer without loading the
whole object into memory. A single call uses concurrent ranges by default;
WithDownloadConfig tunes range size and concurrency. Ordered destinations use
bounded range buffering. Each independent download has its own buffer costs
and progress.
Files.Upload streams plaintext through the OpenTDF encryptor without a fixed
64 GiB size cap. Multipart part sizes grow with the input to stay within the
part-count limit. The effective part size multiplied by Concurrency + 1 must
fit UploadConfig.MaxBufferBytes, which defaults to 2 GiB and can be increased.
The extra buffer holds a part while other parts upload. This is a nominal
per-upload part-buffer budget, not a total process-memory limit; uploader,
encryption, and manifest allocations need additional headroom.
The package maps service errors to sentinel errors while preserving the
underlying service error, including its message. Storage-transfer errors use
generic messages while wrapped causes remain available through errors.Is and
errors.As. An *UploadError means the bytes were stored but
completion could not be confirmed. Check the file with
Look up a file. If it is COMPLETED, the upload succeeded.
If it is still PENDING, there is no public finalize or resume operation;
retrying registers and uploads a new file. The original pending record may block
folder deletion until it is reconciled.
Quick example
// Create a workspace
workspace, err := collaborateClient.Workspaces.Create(ctx, collaborate.CreateWorkspaceInput{
Name: "q3-financials",
Description: "Q3 revenue review",
})
if err != nil {
log.Fatal(err)
}
// Optionally create a folder at the workspace root.
folder, err := collaborateClient.Workspace(workspace).Folders.Create(ctx, collaborate.CreateFolderInput{
Name: "reports",
})
if err != nil {
log.Fatal(err)
}
source, err := os.Open("revenue.xlsx")
if err != nil {
log.Fatal(err)
}
defer source.Close()
folderID := folder.ID()
file, err := collaborateClient.Workspace(workspace).Files.Upload(ctx, collaborate.UploadRequest{
Folder: &folderID, // Omit to upload to the workspace root.
Body: source,
Filename: "q3-revenue.xlsx", // Optional; renames the file on upload.
MimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(file.GetStatus()) // completed
Methods
The client has root-level method groups for cross-workspace operations and workspace-bound groups for operations that must remain in a workspace:
collaborateClient.Workspaces— workspace lifecyclecollaborateClient.Files— look up file metadata and download a raw TDF by file IDcollaborateClient.Workspace(workspace).Files— delete, encrypt/upload, and TDF upload; its lookup and download methods reject files outsideworkspacecollaborateClient.Workspace(workspace).Folders— folder lifecycle and browsecollaborateClient.Workspace(workspace).Users— membership changes forworkspace
Most methods accept the WorkspaceRef, FileRef, and FolderRef interfaces,
so you can pass domain objects directly instead of extracting IDs. Files.Delete
and Workspaces.Delete accept string IDs: Files.Delete always fetches the file
to enforce the bound workspace, while Workspaces.Delete passes the ID directly to
Virtru Collaborate's workspace-delete RPC without fetching the workspace first. See
Typed identifiers.
For an existing workspace, pass a WorkspaceSummary from Workspaces.List or a
WorkspaceID from WorkspaceFromUUID to Client.Workspace; creation is not
required for workspace-bound operations.
NewClient
Constructs a Collaborate client that inherits authentication, endpoint, and common transport settings from the parent Virtru SDK.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Bounds construction-time work; a nil context is treated as context.Background() |
sdk | *virtru.SDK | Yes | Initialized parent SDK |
opts | ...Option | No | Client configuration |
Example
collaborateClient, err := collaborate.NewClient(ctx, sdk,
collaborate.WithUserAgent("my-app/1.0"),
collaborate.WithUploadConfig(collaborate.UploadConfig{Concurrency: 4}),
)
Returns
*Client, or ErrSaaSOnly for a non-SaaS parent SDK unless
WithLocalEndpoint is configured for local development. Invalid
client options return ErrInvalidArgument; missing SDK authentication or
connection state can return ErrInternal or ErrInvalidArgument.
Workspaces.Create
Registers a new workspace.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
in.Name | string | Yes | Workspace name |
in.Description | string | No | Free-text description |
in.Security | *SecuritySettings | No | Initial watermark setting; nil leaves watermark off |
Example
workspace, err := collaborateClient.Workspaces.Create(ctx, collaborate.CreateWorkspaceInput{
Name: "q3-financials",
Description: "Q3 revenue review",
Security: &collaborate.SecuritySettings{Watermark: true},
})
if err != nil {
log.Fatal(err)
}
Returns
*Workspace — the server-assigned workspace with its ID, org ID,
owner entity, and an empty member list. Invalid input returns
ErrInvalidArgument; a duplicate name can return ErrAlreadyExists.
Workspaces.Get
Fetches a workspace by ID.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
id | WorkspaceRef | Yes | Workspace reference — *Workspace, *WorkspaceSummary, or WorkspaceID |
Example
workspace, err := collaborateClient.Workspaces.Get(ctx, collaborate.WorkspaceFromUUID(id))
if err != nil {
log.Fatal(err)
}
Returns
*Workspace — the workspace; ErrNotFound when no
workspace matches.
Workspaces.List
Returns a lazy-paginating iterator over all workspaces visible to the caller.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
opts | ...ListWorkspacesOption | No | Per-call options for filtering and sorting workspaces |
WithFilter accepts a collaborate.WorkspacesFilter message. Its Search is a
case-insensitive partial match against the workspace name or owner email. Its
Owner selects all accessible workspaces (unspecified or
collaborate.WorkspacesOwnerAll) or only workspaces the caller owns
(collaborate.WorkspacesOwnedByMe). If WithFilter is repeated, the last option
wins; WithFilter(nil) omits the filter.
WithSort accepts a handlers.WorkspacesSort message. It can order by
workspace name, owner email, file count, member count, or last modified time,
ascending or descending. Without WithSort, the service defaults to last
modified, most recent first. A supplied sort with an unspecified field or
direction uses the service's default for that choice. If WithSort is repeated,
the last option wins; WithSort(nil) omits the sort.
Example: filter
import "go.pkg.virtru.com/virtru-sdk-go/collaborate"
filter := &collaborate.WorkspacesFilter{
Search: "finance",
Owner: collaborate.WorkspacesOwnedByMe,
}
it := collaborateClient.Workspaces.List(ctx, collaborate.WithFilter(filter))
for it.Next() {
fmt.Println(it.Item().GetName())
}
if err := it.Err(); err != nil {
log.Fatal(err)
}
Example: filter and sort
import (
"go.pkg.virtru.com/virtru-sdk-go/collaborate"
sortcommon "go.pkg.virtru.com/virtru-sdk-go/gen/common"
"go.pkg.virtru.com/virtru-sdk-go/gen/dataharbor/v1/handlers"
)
filter := &collaborate.WorkspacesFilter{
Search: "finance",
Owner: collaborate.WorkspacesOwnedByMe,
}
sort := &handlers.WorkspacesSort{
Field: handlers.WorkspacesSortField_WORKSPACES_SORT_FIELD_NAME,
Direction: sortcommon.SortDirection_SORT_DIRECTION_ASC,
}
it := collaborateClient.Workspaces.List(ctx,
collaborate.WithFilter(filter),
collaborate.WithSort(sort),
)
for it.Next() {
fmt.Println(it.Item().GetName())
}
if err := it.Err(); err != nil {
log.Fatal(err)
}
Returns
*Iterator[*WorkspaceSummary] — an auto-paging iterator; each item
is a WorkspaceSummary. Request failures surface
from Iterator.Err() as mapped service errors.
Workspaces.CheckNameExists
Reports whether a workspace with the given name already exists in the caller's organization.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
name | string | Yes | Workspace name to check |
Example
exists, err := collaborateClient.Workspaces.CheckNameExists(ctx, "q3-financials")
if err != nil {
log.Fatal(err)
}
Returns
bool — true when a workspace with that name exists in the caller's
organization. An empty name can return ErrInvalidArgument.
Workspaces.UpdateSecuritySettings
Changes a workspace's watermark setting and returns the updated workspace. Only the workspace owner may update it.
These settings configure read-time policy obligations for files in the
workspace. They do not add or remove workspace members, and they do not change
whether a recipient is authorized to access a file. The controls are enforced
when a policy-enforcing client reads the TDF; DownloadTDF continues to return
the raw encrypted TDF.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
ref | WorkspaceRef | Yes | Workspace reference — *Workspace, *WorkspaceSummary, or WorkspaceID |
in | UpdateSecuritySettingsInput | Yes | Watermark setting; the field must be non-nil. |
UpdateSecuritySettingsInput fields:
| Field | Type | Description |
|---|---|---|
Watermark | *bool | Enable file watermarking on view; nil leaves it unchanged |
Example
watermark := true
workspace, err := collaborateClient.Workspaces.UpdateSecuritySettings(
ctx,
collaborate.WorkspaceFromUUID(id),
collaborate.UpdateSecuritySettingsInput{Watermark: &watermark},
)
if err != nil {
log.Fatal(err)
}
Returns
*Workspace — the updated workspace, with
GetSecurity() populated. An in with a nil Watermark or a
missing ref returns ErrInvalidArgument; a non-owner caller (or unknown
workspace) returns ErrNotFound.
Workspaces.Delete
Virtru Collaborate soft-deletes the workspace and its files. Their records remain
as tombstones. Folders do not have a soft-delete state. The delete operation
leaves folder records in place until cleanup, which hard-deletes them. A direct
link cannot bypass the deletion. Requests for the deleted workspace or its files
return ErrNotFound. Virtru Collaborate currently has no restore operation.
Only the workspace owner can delete a workspace. A missing, already-deleted, or
non-owner workspace returns ErrNotFound. Other service errors are forwarded with
their Connect code intact. The deleted workspace's name remains reserved within
the organization. Reusing it could create a security risk for TDFs that were
downloaded before deletion. An empty workspaceID returns ErrInvalidArgument
without an RPC. The SDK performs no preflight lookup, UUID validation, retry, or
delete-specific error translation.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
workspaceID | string | Yes | ID of the workspace to soft-delete |
Example
if err := collaborateClient.Workspaces.Delete(ctx, workspaceID); err != nil {
if errors.Is(err, collaborate.ErrNotFound) {
// The workspace is missing, already deleted, or owned by another user.
return
}
log.Fatal(err)
}
Returns
error — nil on success; otherwise the Virtru Collaborate error with the client's
standard sentinel mapping.
Look up a file
Fetches file metadata by ID. Call it through collaborateClient.Files.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
id | FileRef | Yes | File reference — *WorkspaceFile, FileID, or WorkspaceItem.FileID() |
Example
file, err := collaborateClient.Files.Get(ctx, collaborate.FileFromUUID(id))
if err != nil {
log.Fatal(err)
}
Returns
*WorkspaceFile — the file; ErrNotFound
when no file matches. Files.Get does not resolve or attach a share link. The
root lookup is therefore safe to use for recovery when file metadata is needed
without a workspace lookup.
Resolve a file share URL
Resolves the Collaborate UI link for a completed file. This is a separate, explicit operation because resolving the link can require an additional workspace RPC and should not delay ordinary metadata or transfer operations.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context for file and workspace lookups |
fileID | string | Yes | Workspace file UUID |
Example
shareURL, err := collaborateClient.Workspace(workspace).Files.GetShareURL(ctx, fileID)
if err != nil {
log.Fatal(err)
}
if shareURL != "" {
fmt.Println(shareURL)
}
The method validates that the file belongs to the workspace. It returns an
empty string for a file that is not completed. A fetched *Workspace with a
share URL avoids an extra GetWorkspace RPC; an ID, summary, or workspace
without a share URL requires that lookup. Workspace lookup and malformed or
empty share URLs are returned as errors from this explicit operation.
Files.DownloadTDF, Files.Upload, Files.Delete, and
Files.Get do not resolve file share links. Their caller context remains
available for the operation requested. Use the root client.Files.Get as the
linkless recovery lookup when only authoritative file metadata is needed.
Download a stored TDF
Fetches the authoritative file metadata, then streams the stored TDF to any
io.Writer. The SDK does not decrypt the file or evaluate its obligations.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
in.File | FileRef | Yes | File reference: *WorkspaceFile, FileID, or WorkspaceItem.FileID() |
in.Destination | io.Writer | Yes | Destination for the raw TDF bytes |
in.OnProgress | func(int64) | No | Receives cumulative raw-TDF bytes accepted by the destination; serial and monotonic |
in.OnPartOutcome | func(context.Context, DownloadPartResult) | No | Final result for each dispatched range; may run concurrently and out of order |
Download configuration
Pass WithDownloadConfig(DownloadConfig{...}) when creating the Collaborate
client. Zero fields select defaults: 16 MiB ranges and concurrency 4. Part sizes
must be 1–256 MiB and concurrency 1–64. Concurrency: 1 uses a serial GET
without ranged-body retries or range outcomes.
For direct writes to offsets, the destination must implement both io.WriterAt
and io.Seeker, pass the write/seek probes, and report a regular file if it
exposes Stat. A regular file opened without append mode is suitable. A
wrapper that hides these interfaces uses ordered buffering instead.
Ordered writers, including stdout and pipes, use a range window of
max(1, min(Concurrency, floor(64 MiB / PartSize))). Defaults allow 64 MiB of
range buffers per download. A 128 MiB range uses one slot and still needs a
128 MiB buffer. This limit excludes caller-owned buffers and other process
allocations. Slow early ranges can stall ordered output.
DownloadPartResult
| Field | Type | Meaning |
|---|---|---|
PartNumber | int | One-based range position in offset order, not a completion count or upload part number |
TotalParts | int | Planned range count, including the first and final short range; zero until size is known |
Offset | int64 | Byte offset in the raw TDF |
SizeBytes | int64 | Bytes accepted by the destination, including partial writes and bytes left by previous attempts |
Err | error | Final range error, or nil for success |
Callbacks may run concurrently, arrive out of order, and receive an already
cancelled context. Protect shared state. Discarded ordered buffers report zero
accepted bytes. A failed initial ranged request or content-type check reports
range 1 with TotalParts: 0; a small ranged object reports 1 of 1. Once size is
known, TotalParts is stable. Cancellation may leave planned ranges
undispatched, so do not wait for that many callbacks. Serial downloads and
successful whole-object fallbacks emit no outcomes. Sibling cancellation
errors can follow the initiating range failure.
Progress counts unique bytes accepted by the destination, not a contiguous prefix for random-access output. Ranged bodies get at most three attempts with cancellable 200 ms and 400 ms delays. Request retries remain the storage client's responsibility. Retries pin ETag, content type, and total size, and do not retry destination failures or changed representations. Random-access rewrites are not counted twice; ordered output validates each range, including the first, before emitting it. Serial GETs and whole-object fallbacks do not get these body retries.
Example
dst, err := os.CreateTemp(".", ".report-*.tdf")
if err != nil {
log.Fatal(err)
}
tempName := dst.Name()
file, downloadErr := collaborateClient.Files.DownloadTDF(ctx, collaborate.DownloadTDFRequest{
File: collaborate.FileFromUUID(id),
Destination: dst,
OnProgress: func(written int64) {
fmt.Printf("downloaded %d bytes\n", written)
},
})
closeErr := dst.Close()
if downloadErr != nil {
_ = os.Remove(tempName)
log.Fatal(downloadErr)
}
if closeErr != nil {
_ = os.Remove(tempName)
log.Fatal(closeErr)
}
if err := os.Rename(tempName, "report.tdf"); err != nil {
_ = os.Remove(tempName)
log.Fatal(err)
}
fmt.Printf("downloaded %s\n", file.GetFilename())
Returns
*WorkspaceFile with the server's current metadata. The
method accepts only a completed file and rejects any storage response without a
tdf; content-type prefix before writing bytes. Missing files return
ErrNotFound; invalid input, non-completed files, and non-TDF responses return
ErrInvalidArgument. Storage or destination write failures return ErrInternal;
the destination may contain partial bytes, so write to a temporary file and
rename it only after the download and close succeed. Ranged responses validate
offsets, lengths, ETag, content type, and total size. Cancellation stops requests
and dispatch, but cannot retract accepted bytes or interrupt a caller-owned
writer blocked inside Write.
Files.Upload
Registers a file in the workspace bound by
collaborateClient.Workspace(workspace).Files, encrypts its source content as a
TDF, streams it to workspace storage, and marks the file completed. The source
may contain text, binary data, or any other non-empty content available through
an io.ReadSeeker.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request and transfer context |
in.Folder | *FolderID | No | Destination folder; nil means the workspace root |
in.Filename | string | Conditional | Recorded filename; may be omitted when Body implements Name() string |
in.MimeType | string | No | Inner MIME type; defaults to application/octet-stream |
in.OnBytesRead | func(context.Context, int64) | No | Receives the upload context and cumulative source bytes read; callbacks run on an SDK goroutine |
in.OnPartOutcome | func(context.Context, UploadPartResult) | No | Receives the part request context and each multipart part's final result; see Multipart part outcomes |
in.Body | io.ReadSeeker | Yes | Non-empty source content; the SDK measures it and rewinds to the start before upload |
Multipart part outcomes
OnPartOutcome runs once for each attempted multipart part, after retries,
with its final success or failure. Callbacks may run concurrently and
arrive out of part order; synchronize any shared state in the callback. A
single-request upload does not produce multipart part results. Failures
creating or completing the multipart upload surface through the return error,
without a part callback.
Both upload hooks receive a context that carries the upload's cancellation and
deadline. A callback can derive a shorter context for its own checkpoint work.
Callbacks run inline with reading or part upload, so they must return promptly
and honor cancellation. Set the deadline on ctx passed to Upload to bound
the transfer itself.
UploadPartResult field | Type | Meaning |
|---|---|---|
PartNumber | int32 | Multipart part number, independent of completion order |
SizeBytes | int64 | Part payload size in bytes; 0 if it cannot be determined |
Err | error | nil when the part succeeded; otherwise the final error after retries |
For Files.Upload, SizeBytes measures encrypted TDF payload, while
OnBytesRead counts plaintext bytes read. The byte-read callback can run ahead
of completed storage parts.
Example
source, err := os.Open("revenue.xlsx")
if err != nil {
log.Fatal(err)
}
defer source.Close()
file, err := collaborateClient.Workspace(workspace).Files.Upload(ctx, collaborate.UploadRequest{
Body: source, // Filename is inferred from source.Name()
MimeType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
OnPartOutcome: func(_ context.Context, part collaborate.UploadPartResult) {
log.Printf("part %d: %d bytes, succeeded: %t", part.PartNumber, part.SizeBytes, part.Err == nil)
},
})
if err != nil {
var uploadErr *collaborate.UploadError
if errors.As(err, &uploadErr) {
// Bytes reached storage but completion could not be confirmed. There is
// no separate finalize call; inspect the record before retrying. A
// retry creates a new file, and this pending record may block folder
// deletion until it is reconciled.
rec, getErr := collaborateClient.Files.Get(ctx, uploadErr.FileID)
if getErr != nil || rec.GetStatus() != collaborate.WorkspaceFileStatusCompleted {
log.Fatalf("upload not finalized (file %s): %v", uploadErr.FileID.UUID(), err)
}
file = rec
} else {
log.Fatal(err)
}
}
Returns
*WorkspaceFile in
WorkspaceFileStatusCompleted. Invalid or empty references,
a nil/non-seekable/empty body, or a workspace with no
bound attributes return ErrInvalidArgument or ErrInternal. Service and
transfer failures retain their mapped sentinel. If the SDK cannot confirm completion, the method returns
*UploadError with the file ID. Check the record with
Look up a file. If it is still PENDING, retrying registers
a new file; the original pending record may block folder deletion until it is
reconciled.
Files.Delete
Deletes one file through the workspace-bound file group.
Listing files
There is no dedicated Files.List. List a workspace level with
Folders.ListItems and filter to file-kind items. Items
live in a folder tree, so walk into each folder to reach nested files.
it := collaborateClient.Workspace(workspace).Folders.ListItems(ctx, nil) // nil = workspace root
for it.Next() {
item := it.Item()
if !item.IsFile() {
continue // descend folders via collaborateClient.Workspace(workspace).Folders.ListItems(ctx, item.FolderID())
}
fmt.Println(item.GetName())
// Operate on the file via its FileID:
// f, _ := collaborateClient.Files.Get(ctx, item.FileID())
}
if err := it.Err(); err != nil {
log.Fatal(err)
}
Files.Move
Moves one file to a folder or to the workspace root.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
id | FileRef | Yes | File to move; must carry a non-empty UUID |
dest | FolderRef | No | Destination folder, as a FolderID or *Folder; nil moves the file to the workspace root |
Example
Move a file to the workspace root by passing nil as the destination:
moved, err := collaborateClient.Workspace(workspace).Files.Move(ctx, file, nil)
if err != nil {
log.Fatal(err)
}
fmt.Println(moved.GetWorkspaceFolderID()) // empty at the workspace root
Move a file into a specific folder by passing a FolderID or *Folder:
moved, err := collaborateClient.Workspace(workspace).Files.Move(ctx, file, folder.ID())
if err != nil {
log.Fatal(err)
}
fmt.Println(moved.GetWorkspaceFolderID()) // the destination folder UUID
Returns
*WorkspaceFile, the updated file. Invalid references return
ErrInvalidArgument; service failures retain their mapped sentinel errors.
WorkspaceUsers.Add
Adds a user (identified by email) to a workspace.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
email | string | Yes | Email of the user to add |
opts | ...AddUserOption | No | Per-call options (see below) |
Invitation options
| Option | Description |
|---|---|
WithoutEmailNotification() | Suppresses the "added to workspace" notification email that Virtru Collaborate otherwise sends to the invitee. Use it when distributing the workspace link through your own channel; retrieve the link via Workspace.GetShareURL. By default the email is sent. |
Example
result, err := collaborateClient.Workspace(workspace).Users.Add(ctx, "user@example.com")
if err != nil {
log.Fatal(err)
}
// Suppress the automatic email and distribute the link yourself:
_, err = collaborateClient.Workspace(workspace).Users.Add(ctx, "user@example.com",
collaborate.WithoutEmailNotification())
if err != nil {
log.Fatal(err)
}
// Fetch the full workspace to obtain the shareable link:
full, err := collaborateClient.Workspaces.Get(ctx, workspace)
if err != nil {
log.Fatal(err)
}
shareURL := full.GetShareURL()
Returns
*AddUserResult — carries the server-assigned user ID.
Invalid workspace/email input returns
ErrInvalidArgument; an existing member can return ErrAlreadyExists.
WorkspaceUsers.Remove
Removes a user from a workspace.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
userID | string | Yes | Server-assigned user ID (from WorkspaceUsers.Add) |
Example
if err := collaborateClient.Workspace(workspace).Users.Remove(ctx, userID); err != nil {
log.Fatal(err)
}
Returns
error — invalid workspace or user identifiers return ErrInvalidArgument;
missing resources can return ErrNotFound.
WorkspaceUsers.RemoveByEmail
Removes a user from a workspace by email. Use it when you know the member's
email but not the user ID returned by WorkspaceUsers.Add.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
email | string | Yes | Email of the member to remove |
Example
if err := collaborateClient.Workspace(workspace).Users.RemoveByEmail(ctx, "alice@example.com"); err != nil {
log.Fatal(err)
}
Returns
error — an invalid workspace ID or email returns ErrInvalidArgument;
missing resources can return ErrNotFound.
Folders.Create
Creates a folder in a workspace. A nil Parent places the folder at the
workspace root.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
in.Parent | *FolderID | No | Parent folder; nil places the folder at the workspace root |
in.Name | string | Yes | Folder name: 1–255 chars, no leading/trailing whitespace or control characters |
Example
folder, err := collaborateClient.Workspace(workspace).Folders.Create(ctx, collaborate.CreateFolderInput{
Name: "reports",
})
if err != nil {
log.Fatal(err)
}
Returns
*Folder — the created folder. A duplicate sibling name
returns ErrAlreadyExists; a missing or unentitled workspace/parent returns
ErrNotFound.
Folders.EnsurePaths
Atomically resolves nested folder paths under Parent: it creates missing
ancestors, reuses folders that already exist, and reports which paths this
request created.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
in.Parent | FolderRef | No | Parent folder; nil places paths at the workspace root |
in.Paths | []string | Yes | Slash-separated paths relative to Parent, such as reports/2024/q1 |
Example
resolved, err := collaborateClient.Workspace(workspace).Folders.EnsurePaths(ctx, collaborate.EnsurePathsInput{
Parent: folder,
Paths: []string{"2024/q1", "2024/q2"},
})
if err != nil {
log.Fatal(err)
}
for _, folder := range resolved {
log.Printf("%s: %s (created=%t)", folder.Path(), folder.GetID(), folder.WasCreated())
}
Returns
[]*ResolvedFolder — every resolved folder, including
implicit ancestors, in server order. A rejection returns no partial result.
Invalid input returns ErrInvalidArgument; a missing or unentitled
workspace/parent returns ErrNotFound.
Folders.Rename
Renames a folder.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
folder | FolderID | Yes | The folder to rename; must carry a non-empty UUID |
name | string | Yes | New folder name: 1–255 chars, no leading/trailing whitespace or control characters |
Example
err := collaborateClient.Workspace(workspace).Folders.Rename(ctx, folderID, "renamed-reports")
if err != nil {
log.Fatal(err)
}
Returns
nil on success. Rename does not return an updated *Folder.
Invalid workspace, folder, or name input returns ErrInvalidArgument; a
duplicate sibling name returns ErrAlreadyExists; a missing or unentitled
workspace/folder returns ErrNotFound. Other server errors are forwarded.
Folders.Delete
Deletes a folder and its descendant folders when the subtree contains no live
file record in a state other than FAILED or CANCELED. Soft-deleted files
do not block deletion. Current service code reparents remaining file records
to the workspace root instead of removing them. A blocked deletion returns
the service failed-precondition error to the caller.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
folder | FolderRef | Yes | Folder to delete; must carry a non-empty UUID. nil means the workspace root and is rejected |
Example
if err := collaborateClient.Workspace(workspace).Folders.Delete(ctx, folderID); err != nil {
log.Fatal(err)
}
Returns
error — invalid workspace or folder references return ErrInvalidArgument;
missing or unentitled folders return ErrNotFound; live pending or completed files
under the target are reported as the upstream deletion error. Remaining file
records are reparented to the workspace root by current service code.
Folders.ListItems
Lists the files and folders at one level of a workspace; a nil folder lists the
workspace root.
Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
ctx | context.Context | Yes | Request context |
folder | *FolderID | No | Folder level to list; nil lists the workspace root |
Example
it := collaborateClient.Workspace(workspace).Folders.ListItems(ctx, nil) // nil = workspace root
for it.Next() {
item := it.Item()
if item.IsFolder() {
// descend: collaborateClient.Workspace(workspace).Folders.ListItems(ctx, item.FolderID())
fmt.Println("dir: ", item.GetName())
} else {
fmt.Println("file:", item.GetName(), item.GetSize())
}
}
if err := it.Err(); err != nil {
log.Fatal(err)
}
crumbs := it.Ancestors() // empty at the root
Returns
*ItemIterator — an auto-paging iterator over
WorkspaceItem entries; also exposes a root→leaf breadcrumb via
Ancestors(). Invalid references surface from
Iterator.Err() as
ErrInvalidArgument; request failures use the mapped service sentinels.
Type reference
See the generated Go types for exact getters and signatures. The following behavior matters when using the objects.
Every Get* accessor declared on the types below is nil-safe: called on a
nil receiver it returns the zero value rather than panicking, so chained
access like workspace.GetOwnerEntity().GetEmail() is always safe. The one
exception is a getter promoted from an embedded pointer — a nil
*ResolvedFolder panics on the embedded *Folder getters
(GetID() and friends), because reaching the embed dereferences the outer
nil. This is not a case the SDK produces: EnsurePaths never returns a nil
element, and a returned ResolvedFolder with a nil embedded *Folder is
itself safe (the Folder getters guard their own nil receiver).
Timestamp getters return the zero time.Time when the service omits the
timestamp. Check IsZero() before displaying or comparing one.
The result types below implement json.Marshaler. json.Marshal on a result,
a slice of results, or a struct or map that contains them writes the protobuf
JSON of the service message the result was mapped from, whether each result is
held by pointer or by value. Field names are proto names,
such as workspace_folder_id. Default scalar values stay present, int64 values
encode as strings, enums use their full names (such as
WORKSPACE_FILE_STATUS_COMPLETED), and absent timestamps are omitted. The
output leaves out the storage location of files and items and the workspace
protected_download setting.
AddUserResult
Returned by WorkspaceUsers.Add.
| Method | Return type | Description |
|---|---|---|
GetUserID() | string | Server-assigned user ID |
MarshalJSON() | []byte, error | Protobuf JSON of the service message |
ResolvedFolder
One resolved folder returned by Folders.EnsurePaths. It
embeds *Folder, so folder accessors such as GetID() are available
directly.
| Method | Return type | Description |
|---|---|---|
Path() | string | Path relative to the request parent |
WasCreated() | bool | Whether this request inserted the folder |
MarshalJSON() | []byte, error | Protobuf JSON of the service message, with the folder under workspace_folder |
Entity
The authenticated caller — a Person Entity (a human via SSO) or a Non-Person Entity (an M2M client). Appears as the owner or a member on the shapes above.
| Method | Return type | Description |
|---|---|---|
GetID() | string | Entity UUID |
GetEmail() | string | Entity email |
GetCreatedAt() | time.Time | Creation timestamp |
GetUpdatedAt() | time.Time | Last-update timestamp |
MarshalJSON() | []byte, error | Protobuf JSON of the service message |
Folder
Returned by Folders.Create and embedded in
ResolvedFolder.
| Method | Return type | Description |
|---|---|---|
ID() | FolderID | Typed identifier |
GetID() | string | Folder UUID |
GetWorkspaceID() | string | Parent workspace ID |
GetParentID() | string | Parent folder ID (empty at the workspace root) |
GetName() | string | Folder name |
GetOwnerEntity() | *Entity | The folder owner |
GetCreatedAt() | time.Time | Creation timestamp |
GetUpdatedAt() | time.Time | Last-update timestamp |
MarshalJSON() | []byte, error | Protobuf JSON of the service message |
FolderAncestor
A breadcrumb entry from ItemIterator.Ancestors().
| Method | Return type | Description |
|---|---|---|
GetID() | string | Folder UUID |
GetName() | string | Folder name |
MarshalJSON() | []byte, error | Protobuf JSON of the service message |
ItemKind
An int32 enum distinguishing a WorkspaceItem's kind
(WorkspaceItem.Kind). IsFile() / IsFolder() are convenience checks; both
return false when the kind is ItemKindUnspecified.
| Constant | Value | Description |
|---|---|---|
ItemKindUnspecified | 0 | Zero value / unknown |
ItemKindFile | 1 | The item is a file |
ItemKindFolder | 2 | The item is a folder |
UploadError
Returned when the SDK cannot confirm that an upload completed. Its FileID
identifies the file to check by looking up the file. If it is
COMPLETED, the upload succeeded. If it is still PENDING, there is no finalize
or resume operation. Retrying registers and uploads a new file; the original
pending record may block folder deletion until it is reconciled.
| Field / method | Type | Description |
|---|---|---|
FileID | FileID | Registered file whose bytes are already stored |
Err | error | Underlying completion or metadata-fetch error |
Error() | string | Human-readable failure |
Unwrap() | error | Supports errors.Is and errors.As |
Workspace
Returned by Workspaces.Create and Workspaces.Get.
| Method | Return type | Description |
|---|---|---|
ID() | WorkspaceID | Typed identifier for passing to other methods |
GetID() | string | Workspace UUID |
GetOrgID() | string | Owning organization ID |
GetName() | string | Workspace name |
GetDescription() | string | Free-text description |
GetAttributes() | []string | Attribute FQNs on the workspace |
GetOwnerEntity() | *Entity | The workspace owner |
GetMemberEntities() | []*Entity | Workspace members |
GetCreatedAt() | time.Time | Creation timestamp |
GetUpdatedAt() | time.Time | Last-update timestamp |
GetShareURL() | string | Tenant-aware URL for landing on the workspace |
GetSecurity() | *SecuritySettings | Security settings, or nil when unpopulated (as on List) |
MarshalJSON() | []byte, error | Protobuf JSON of the service message, without protected_download |
SecuritySettings configures how files in a workspace are handled when read; it
does not grant workspace membership or determine whether a caller is authorized
to access the workspace. Fields: Watermark bool requires a compatible viewer
to watermark rendered content.
WorkspaceFile
Returned by Files.Upload,
a root file lookup, and a stored-TDF download.
| Method | Return type | Description |
|---|---|---|
ID() | FileID | Typed identifier |
GetID() | string | File UUID |
GetWorkspaceID() | string | Parent workspace ID |
GetWorkspaceFolderID() | string | Containing folder ID (empty at the workspace root) |
GetFilename() | string | File name |
GetMimeType() | string | File media type |
GetSize() | int64 | Declared byte length |
GetAttributes() | []string | Attribute FQNs on the file |
GetOwnerEntity() | *Entity | The file owner |
GetStatus() | WorkspaceFileStatus | Upload status of the file |
GetTdfPolicyID() | string | TDF ID recorded for the file; empty when unavailable |
GetCreatedAt() | time.Time | Creation timestamp |
GetUpdatedAt() | time.Time | Last-update timestamp |
MarshalJSON() | []byte, error | Protobuf JSON of the service message, without location |
Files.Upload automatically records the TDF ID for the
upload. Read it with GetTdfPolicyID() after upload, or from a file returned
by a root file lookup. Files created or completed outside these helpers can
return an empty string when no TDF ID is available.
The TDF ID is the UUID of the policy object embedded in the TDF manifest, not a workspace file ID or an attribute.
WorkspaceFile does not carry a file share URL. To resolve one, call the
explicit workspace-scoped Files.GetShareURL
operation. It is a UI link, not a download URL or storage URL; ordinary file
lookups and transfers remain independent of its availability.
WorkspaceFileStatus
An int32 enum for a file's upload lifecycle. String() renders pending /
completed / failed / canceled; any other value (including the zero value)
renders unspecified.
| Constant | Value | Description |
|---|---|---|
WorkspaceFileStatusUnspecified | 0 | Zero value / unknown |
WorkspaceFileStatusPending | 1 | Registered; bytes not yet finalized |
WorkspaceFileStatusCompleted | 2 | Upload finalized successfully |
WorkspaceFileStatusFailed | 3 | Upload failed |
WorkspaceFileStatusCanceled | 4 | Upload canceled by the user |
WorkspaceItem
A single entry from Folders.ListItems — either a file or a
folder.
| Method | Return type | Description |
|---|---|---|
Kind() | ItemKind | ItemKindFile, ItemKindFolder, or ItemKindUnspecified |
IsFile() | bool | True when the item is a file |
IsFolder() | bool | True when the item is a folder |
GetID() | string | Item UUID |
GetParentID() | string | Containing folder ID |
GetName() | string | Item name |
GetMimeType() | string | Media type (files only) |
GetSize() | int64 | Byte length (files only) |
GetOwnerEntity() | *Entity | The item owner |
GetUpdatedAt() | time.Time | Last-update timestamp |
FolderID() | *FolderID | Typed folder ID for descending (folders only; nil for files) |
FileID() | *FileID | Typed file ID for file operations (files only; nil for folders) |
MarshalJSON() | []byte, error | Protobuf JSON of the service message, without location |
WorkspaceSummary
The lighter shape returned by Workspaces.List — aggregate
counts instead of a member slice or description.
| Method | Return type | Description |
|---|---|---|
ID() | WorkspaceID | Typed identifier |
GetID() | string | Workspace UUID |
GetOrgID() | string | Owning organization ID |
GetName() | string | Workspace name |
GetAttributes() | []string | Attribute FQNs on the workspace |
GetMemberCount() | int32 | Number of members |
GetFileCount() | int32 | Number of files |
GetTotalFileSize() | int64 | Total size of all files, in bytes |
GetUpdatedAt() | time.Time | Last-update timestamp |
GetOwnerEntity() | *Entity | The workspace owner |
MarshalJSON() | []byte, error | Protobuf JSON of the service message |
Iterators
Workspaces.List and
Folders.ListItems return lazy, auto-paging iterators. The
generic Iterator[T] and ItemIterator share the same loop shape:
for it.Next() {
item := it.Item()
// ...
}
if err := it.Err(); err != nil {
// a fetch failed; err is one of the sentinels below
}
ItemIterator additionally exposes
Ancestors(), which returns a slice of
FolderAncestor objects representing the root→leaf
breadcrumb to the requested folder. It is populated after the first
Next().
Options
| Option | Default | Description |
|---|---|---|
WithUserAgent(ua) | "" | Appends a User-Agent suffix to outgoing requests |
WithPageSize(n) | 0 (uses DefaultPageSize, 100) | Default page size for List* operations; a negative value is rejected by NewClient |
WithConnectInterceptors(...) | — | Appends Connect-RPC interceptors (tracing, metrics — not auth) |
WithConnectOptions(...) | — | Appends raw Connect-RPC client options for this client; common options configured with virtru.WithExtraClientOptions are inherited automatically |
WithUploadConfig(c) | 28 MiB parts, concurrency 2, 2 GiB buffer budget | Sets multipart upload tuning. PartSize must be between 5 MiB and 5 GiB; Concurrency cannot be negative. MaxBufferBytes sets the nominal per-upload part-buffer budget (zero uses 2 GiB; negative values are invalid). The effective part size × (Concurrency + 1) must fit this budget. Other allocations need additional memory. |
WithLocalEndpoint(port...) | Port 8081 | Local development only; targets 127.0.0.1 and requires the parent endpoint to resolve exclusively to loopback |
Typed identifiers
Most methods accept the WorkspaceRef, FileRef, and FolderRef interfaces,
so you can pass domain objects directly without extracting IDs. Files.Delete
and Workspaces.Delete accept string IDs: Files.Delete performs the
workspace-scoped lookup itself, while Workspaces.Delete passes the ID directly
to Virtru Collaborate's workspace-delete RPC. FolderRef accepts FolderID and *Folder;
nil means the workspace root.
// Anything that satisfies WorkspaceRef: *Workspace, *WorkspaceSummary, WorkspaceID
collaborateClient.Workspace(workspace).Folders.ListItems(ctx, nil) // *Workspace
collaborateClient.Workspace(summary).Folders.ListItems(ctx, nil) // *WorkspaceSummary
collaborateClient.Workspace(collaborate.WorkspaceFromUUID("...")).Folders.ListItems(ctx, nil) // WorkspaceID
// Anything that satisfies FileRef: *WorkspaceFile, FileID, WorkspaceItem.FileID()
collaborateClient.Files.Get(ctx, file) // *WorkspaceFile
collaborateClient.Files.Get(ctx, collaborate.FileFromUUID("...")) // FileID
collaborateClient.Files.Get(ctx, item.FileID()) // from Folders.ListItems (file-kind item; nil for folders)
collaborateClient.Workspace(workspace).Files.Delete(ctx, item.FileID().UUID()) // raw file ID
// Anything that satisfies FolderRef: *Folder or FolderID
collaborateClient.Workspace(workspace).Files.Move(ctx, file, folder) // *Folder
collaborateClient.Workspace(workspace).Files.Move(ctx, file, folder.ID()) // FolderID from folder.ID()
// Folder handles for browse methods: from Folder.ID() or constructed from a UUID
fid := collaborate.FolderFromUUID("...")
collaborateClient.Workspace(workspace).Folders.ListItems(ctx, &fid) // FolderID constructed from a UUID
Constructors WorkspaceFromUUID, FileFromUUID, and FolderFromUUID build
typed IDs from wire-level UUID strings.
| Type | Accepted by | Accessor |
|---|---|---|
FileID | Any FileRef parameter | UUID() string |
FolderID | Folder placement, browse, and move parameters | UUID() string |
FolderRef | File moves and Folders.EnsurePaths parent | FolderID or *Folder |
WorkspaceID | Any WorkspaceRef parameter | UUID() string |
Error handling
The Collaborate package maps service errors to sentinel errors, so callers can
branch with errors.Is:
| Sentinel | Meaning |
|---|---|
ErrSaaSOnly | NewClient received an SDK that is not connected to Virtru SaaS |
ErrNotFound | Resource doesn't exist (or is concealed by authorization) |
ErrInvalidArgument | Bad input |
ErrUnauthenticated | Missing or invalid auth |
ErrPermissionDenied | Insufficient privileges |
ErrAlreadyExists | Duplicate resource |
ErrUnavailable | Service temporarily unavailable |
ErrInternal | Server-side error |
The underlying service error remains in the error chain, including its message.
Storage-transfer errors use generic messages while retaining their wrapped
causes. Uploads can also return *UploadError when the SDK
cannot confirm completion.
file, err := collaborateClient.Files.Get(ctx, id)
if errors.Is(err, collaborate.ErrNotFound) {
// handle missing file
}
Runnable workflow
After installing the Go SDK and
configuring authentication, save this
complete example as main.go in a module using the Go SDK. Set
WORKSPACE_NAME to an unused name and INITIAL_FILE_PATH to a non-empty local
file, then run go run .. Optionally set RECIPIENT_EMAIL to invite a member.
The invitation sends the default notification email. The example creates real
resources and leaves them available for inspection; it does not automatically
retry failed uploads. Use the recovery example before retrying
an upload whose completion is uncertain.
package main
import (
"context"
"fmt"
"os"
"time"
virtru "go.pkg.virtru.com/virtru-sdk-go"
"go.pkg.virtru.com/virtru-sdk-go/collaborate"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
clientID, secret := os.Getenv("VIRTRU_CLIENT_ID"), os.Getenv("VIRTRU_CLIENT_SECRET")
name, sourcePath := os.Getenv("WORKSPACE_NAME"), os.Getenv("INITIAL_FILE_PATH")
if clientID == "" || secret == "" || name == "" || sourcePath == "" {
return fmt.Errorf("set VIRTRU_CLIENT_ID, VIRTRU_CLIENT_SECRET, WORKSPACE_NAME, and INITIAL_FILE_PATH")
}
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
sdk, err := virtru.New(virtru.WithClientCredentials(clientID, secret, nil))
if err != nil {
return fmt.Errorf("initialize SDK: %w", err)
}
defer sdk.Close()
client, err := collaborate.NewClient(ctx, sdk)
if err != nil {
return fmt.Errorf("initialize Collaborate: %w", err)
}
workspace, err := client.Workspaces.Create(ctx, collaborate.CreateWorkspaceInput{Name: name})
if err != nil {
return fmt.Errorf("create workspace: %w", err)
}
fmt.Printf("workspace ID: %s\n", workspace.GetID())
bound := client.Workspace(workspace)
folder, err := bound.Folders.Create(ctx, collaborate.CreateFolderInput{Name: "reports"})
if err != nil {
return fmt.Errorf("create folder: %w", err)
}
folderID := folder.ID()
source, err := os.Open(sourcePath)
if err != nil {
return fmt.Errorf("open source: %w", err)
}
defer source.Close()
file, err := bound.Files.Upload(ctx, collaborate.UploadRequest{Body: source, Folder: &folderID})
if err != nil {
// See the upload-recovery example before retrying an uncertain completion.
return fmt.Errorf("upload file: %w", err)
}
fmt.Printf("file ID: %s; status: %s\n", file.GetID(), file.GetStatus())
if email := os.Getenv("RECIPIENT_EMAIL"); email != "" {
if _, err := bound.Users.Add(ctx, email); err != nil {
return fmt.Errorf("invite member: %w", err)
}
}
full, err := client.Workspaces.Get(ctx, workspace)
if err != nil {
return fmt.Errorf("check workspace: %w", err)
}
fmt.Printf("workspace link: %s\n", full.GetShareURL())
for _, member := range full.GetMemberEntities() {
fmt.Printf("member: %s (%s)\n", member.GetEmail(), member.GetID())
}
return nil
}
Related
- TDF reference — encryption APIs used by
Files.Upload