Skip to main content

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.

note

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

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 lifecycle
  • collaborateClient.Files — look up file metadata and download a raw TDF by file ID
  • collaborateClient.Workspace(workspace).Files — delete, encrypt/upload, and TDF upload; its lookup and download methods reject files outside workspace
  • collaborateClient.Workspace(workspace).Folders — folder lifecycle and browse
  • collaborateClient.Workspace(workspace).Users — membership changes for workspace

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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesBounds construction-time work; a nil context is treated as context.Background()
sdk*virtru.SDKYesInitialized parent SDK
opts...OptionNoClient 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
in.NamestringYesWorkspace name
in.DescriptionstringNoFree-text description
in.Security*SecuritySettingsNoInitial 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
idWorkspaceRefYesWorkspace 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
opts...ListWorkspacesOptionNoPer-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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
namestringYesWorkspace 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
refWorkspaceRefYesWorkspace reference — *Workspace, *WorkspaceSummary, or WorkspaceID
inUpdateSecuritySettingsInputYesWatermark setting; the field must be non-nil.

UpdateSecuritySettingsInput fields:

FieldTypeDescription
Watermark*boolEnable 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
workspaceIDstringYesID 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
idFileRefYesFile 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context for file and workspace lookups
fileIDstringYesWorkspace 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
in.FileFileRefYesFile reference: *WorkspaceFile, FileID, or WorkspaceItem.FileID()
in.Destinationio.WriterYesDestination for the raw TDF bytes
in.OnProgressfunc(int64)NoReceives cumulative raw-TDF bytes accepted by the destination; serial and monotonic
in.OnPartOutcomefunc(context.Context, DownloadPartResult)NoFinal 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​

FieldTypeMeaning
PartNumberintOne-based range position in offset order, not a completion count or upload part number
TotalPartsintPlanned range count, including the first and final short range; zero until size is known
Offsetint64Byte offset in the raw TDF
SizeBytesint64Bytes accepted by the destination, including partial writes and bytes left by previous attempts
ErrerrorFinal 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest and transfer context
in.Folder*FolderIDNoDestination folder; nil means the workspace root
in.FilenamestringConditionalRecorded filename; may be omitted when Body implements Name() string
in.MimeTypestringNoInner MIME type; defaults to application/octet-stream
in.OnBytesReadfunc(context.Context, int64)NoReceives the upload context and cumulative source bytes read; callbacks run on an SDK goroutine
in.OnPartOutcomefunc(context.Context, UploadPartResult)NoReceives the part request context and each multipart part's final result; see Multipart part outcomes
in.Bodyio.ReadSeekerYesNon-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 fieldTypeMeaning
PartNumberint32Multipart part number, independent of completion order
SizeBytesint64Part payload size in bytes; 0 if it cannot be determined
Errerrornil 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
idFileRefYesFile to move; must carry a non-empty UUID
destFolderRefNoDestination 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
emailstringYesEmail of the user to add
opts...AddUserOptionNoPer-call options (see below)

Invitation options​

OptionDescription
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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
userIDstringYesServer-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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
emailstringYesEmail 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
in.Parent*FolderIDNoParent folder; nil places the folder at the workspace root
in.NamestringYesFolder 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
in.ParentFolderRefNoParent folder; nil places paths at the workspace root
in.Paths[]stringYesSlash-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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
folderFolderIDYesThe folder to rename; must carry a non-empty UUID
namestringYesNew 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
folderFolderRefYesFolder 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​

ParameterTypeRequiredDescription
ctxcontext.ContextYesRequest context
folder*FolderIDNoFolder 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.

MethodReturn typeDescription
GetUserID()stringServer-assigned user ID
MarshalJSON()[]byte, errorProtobuf 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.

MethodReturn typeDescription
Path()stringPath relative to the request parent
WasCreated()boolWhether this request inserted the folder
MarshalJSON()[]byte, errorProtobuf 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.

MethodReturn typeDescription
GetID()stringEntity UUID
GetEmail()stringEntity email
GetCreatedAt()time.TimeCreation timestamp
GetUpdatedAt()time.TimeLast-update timestamp
MarshalJSON()[]byte, errorProtobuf JSON of the service message

Folder​

Returned by Folders.Create and embedded in ResolvedFolder.

MethodReturn typeDescription
ID()FolderIDTyped identifier
GetID()stringFolder UUID
GetWorkspaceID()stringParent workspace ID
GetParentID()stringParent folder ID (empty at the workspace root)
GetName()stringFolder name
GetOwnerEntity()*EntityThe folder owner
GetCreatedAt()time.TimeCreation timestamp
GetUpdatedAt()time.TimeLast-update timestamp
MarshalJSON()[]byte, errorProtobuf JSON of the service message

FolderAncestor​

A breadcrumb entry from ItemIterator.Ancestors().

MethodReturn typeDescription
GetID()stringFolder UUID
GetName()stringFolder name
MarshalJSON()[]byte, errorProtobuf 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.

ConstantValueDescription
ItemKindUnspecified0Zero value / unknown
ItemKindFile1The item is a file
ItemKindFolder2The 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 / methodTypeDescription
FileIDFileIDRegistered file whose bytes are already stored
ErrerrorUnderlying completion or metadata-fetch error
Error()stringHuman-readable failure
Unwrap()errorSupports errors.Is and errors.As

Workspace​

Returned by Workspaces.Create and Workspaces.Get.

MethodReturn typeDescription
ID()WorkspaceIDTyped identifier for passing to other methods
GetID()stringWorkspace UUID
GetOrgID()stringOwning organization ID
GetName()stringWorkspace name
GetDescription()stringFree-text description
GetAttributes()[]stringAttribute FQNs on the workspace
GetOwnerEntity()*EntityThe workspace owner
GetMemberEntities()[]*EntityWorkspace members
GetCreatedAt()time.TimeCreation timestamp
GetUpdatedAt()time.TimeLast-update timestamp
GetShareURL()stringTenant-aware URL for landing on the workspace
GetSecurity()*SecuritySettingsSecurity settings, or nil when unpopulated (as on List)
MarshalJSON()[]byte, errorProtobuf 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.

MethodReturn typeDescription
ID()FileIDTyped identifier
GetID()stringFile UUID
GetWorkspaceID()stringParent workspace ID
GetWorkspaceFolderID()stringContaining folder ID (empty at the workspace root)
GetFilename()stringFile name
GetMimeType()stringFile media type
GetSize()int64Declared byte length
GetAttributes()[]stringAttribute FQNs on the file
GetOwnerEntity()*EntityThe file owner
GetStatus()WorkspaceFileStatusUpload status of the file
GetTdfPolicyID()stringTDF ID recorded for the file; empty when unavailable
GetCreatedAt()time.TimeCreation timestamp
GetUpdatedAt()time.TimeLast-update timestamp
MarshalJSON()[]byte, errorProtobuf 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.

ConstantValueDescription
WorkspaceFileStatusUnspecified0Zero value / unknown
WorkspaceFileStatusPending1Registered; bytes not yet finalized
WorkspaceFileStatusCompleted2Upload finalized successfully
WorkspaceFileStatusFailed3Upload failed
WorkspaceFileStatusCanceled4Upload canceled by the user

WorkspaceItem​

A single entry from Folders.ListItems — either a file or a folder.

MethodReturn typeDescription
Kind()ItemKindItemKindFile, ItemKindFolder, or ItemKindUnspecified
IsFile()boolTrue when the item is a file
IsFolder()boolTrue when the item is a folder
GetID()stringItem UUID
GetParentID()stringContaining folder ID
GetName()stringItem name
GetMimeType()stringMedia type (files only)
GetSize()int64Byte length (files only)
GetOwnerEntity()*EntityThe item owner
GetUpdatedAt()time.TimeLast-update timestamp
FolderID()*FolderIDTyped folder ID for descending (folders only; nil for files)
FileID()*FileIDTyped file ID for file operations (files only; nil for folders)
MarshalJSON()[]byte, errorProtobuf JSON of the service message, without location

WorkspaceSummary​

The lighter shape returned by Workspaces.List — aggregate counts instead of a member slice or description.

MethodReturn typeDescription
ID()WorkspaceIDTyped identifier
GetID()stringWorkspace UUID
GetOrgID()stringOwning organization ID
GetName()stringWorkspace name
GetAttributes()[]stringAttribute FQNs on the workspace
GetMemberCount()int32Number of members
GetFileCount()int32Number of files
GetTotalFileSize()int64Total size of all files, in bytes
GetUpdatedAt()time.TimeLast-update timestamp
GetOwnerEntity()*EntityThe workspace owner
MarshalJSON()[]byte, errorProtobuf 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​

OptionDefaultDescription
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 budgetSets 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 8081Local 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.

TypeAccepted byAccessor
FileIDAny FileRef parameterUUID() string
FolderIDFolder placement, browse, and move parametersUUID() string
FolderRefFile moves and Folders.EnsurePaths parentFolderID or *Folder
WorkspaceIDAny WorkspaceRef parameterUUID() string

Error handling​

The Collaborate package maps service errors to sentinel errors, so callers can branch with errors.Is:

SentinelMeaning
ErrSaaSOnlyNewClient received an SDK that is not connected to Virtru SaaS
ErrNotFoundResource doesn't exist (or is concealed by authorization)
ErrInvalidArgumentBad input
ErrUnauthenticatedMissing or invalid auth
ErrPermissionDeniedInsufficient privileges
ErrAlreadyExistsDuplicate resource
ErrUnavailableService temporarily unavailable
ErrInternalServer-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.

main.go
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
}