Go SDK

Use the Go SDK to moderate content, manage assets and handle events from your server, with typed responses, context cancellation, streamed transfers and pagination iterators. It requires Go 1.22 or later and uses only the standard library. The Go SDK reference describes every option and behaviour in detail.

Install

go get github.com/CalmLens/sdks/go@latest

See Versioning and support for what each version change means and where to find the changelog.

Moderate content

Create an API key and copy your project ID as described in Authentication, and keep them on your server. Each network method accepts a context.Context and returns an error. Assets.Create queues processing; Assets.Classify and Text.Classify wait for the decision. Audio and video always run in the background. See Waiting for the decision for supported content, webhooks and polling.

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	calmlens "github.com/CalmLens/sdks/go"
)

func main() {
	client, err := calmlens.NewServerClient(calmlens.Options{
		APIKey:    os.Getenv("CALMLENS_API_KEY"),
		ProjectID: os.Getenv("CALMLENS_PROJECT_ID"),
	})
	if err != nil {
		log.Fatal(err)
	}
	asset, err := client.Text.Classify(context.Background(), calmlens.ClassifyTextOptions{
		Text:       "Great photo!",
		ExternalID: calmlens.Ptr("comment-42"),
	})
	if err != nil {
		log.Fatal(err)
	}
	if asset.Classification.Moderation.Status == calmlens.ModerationStatusAllowed {
		fmt.Println("Allowed", asset.ID)
	}
}

Publish allowed content normally and limited content with reduced reach. Serve age-restricted content only to viewers your app allows, by setting ViewerClaims: &calmlens.ViewerClaims{AgeConfirmed: calmlens.Ptr(true)} in CDNAssetURLOptions (which CDNServeOptions embeds) or SignAssetURLOptions; a signed URL or your API key alone doesn't serve it. See Age-restricted assets. A category with no score is unknown, rather than safely zero. Treat a status you don't recognise as not allowed. See Reading classification results.

Waiting for a decision

Assets.WaitForDecision retrieves the asset at once, then again after 0.5 seconds, waiting 1.5 times longer each time, up to 2 seconds between checks, until its classification.status is completed or failed, and returns it.

  • Timeout is a *time.Duration: set it with calmlens.Ptr(30 * time.Second). Left nil, it is calmlens.DefaultDecisionTimeout (60 seconds), and calmlens.Ptr(time.Duration(0)) checks once.
  • If there is no decision within Timeout, it returns sdk/timeout with Details {"assetId", "classificationStatus", "moderationStatus"}.
  • Cancel ctx to stop early (sdk/cancelled).

Uploads

Inside your application, using the client above:

ctx := context.Background()
file, err := os.Open("photo.jpg")
if err != nil {
	log.Fatal(err)
}
defer file.Close()
queued, err := client.Assets.Create(ctx, calmlens.SubmitAssetOptions{
	Name:              "photo.jpg",
	Content:           &calmlens.Content{Type: "image/jpeg", Data: file},
	Visibility:        "private",
	ProcessingOptions: &calmlens.ProcessingOptions{KeepContentAfterProcessing: calmlens.Ptr(true)},
})
if err != nil {
	log.Fatal(err)
}

// Wait for the decision, retrieve it later, or respond to an asset.allowed or asset.blocked webhook.
current, err := client.Assets.WaitForDecision(ctx, calmlens.WaitForDecisionOptions{AssetID: queued.ID})
if err != nil {
	log.Fatal(err)
}
if current.Classification.Moderation.Status == calmlens.ModerationStatusAllowed {
	signed, err := client.CDN.SignAssetURL(ctx, calmlens.SignAssetURLOptions{
		AssetID: current.ID, Original: true, Resource: calmlens.ResourceOriginal, ExpiresIn: 60,
	})
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(signed.URL)
}

Data readers are streamed without buffering. Binary uploads have no deadline unless you set Options.UploadTimeout, so large transfers are never cut off: bound them with a context deadline. To upload from a link, set URL instead of Content: CalmLens downloads the file, up to 10 MiB for images and 20 MiB for other files. See Assets API for upload limits.

Content larger than Options.PartSizeBytes (8 MiB by default) that the client can read again, such as Bytes or an *os.File with SizeInBytes, is sent as a multipart upload for you: each part is retried on its own, and calling again with the same IdempotencyKey resumes an interrupted upload. To send the parts yourself, multipart readers need an exact SizeInBytes, and parts are sent sequentially. SubmitAssetOptions.TotalSizeInBytes declares the whole file size up front. Whether the upload was started with Assets.Create (queued) or Assets.Classify (wait for the decision) is fixed by the first part, so any process can finish it with the asset ID; UploadAssetPartOptions.Wait overrides it.

Each upload must be a supported type within that type's size and duration limits; see Asset types and limits. Documents are PDF, DOCX, DOC, RTF and ODT files, spreadsheets (XLSX, XLSM, XLS, ODS) and presentations (PPTX, PPTM, PPT, ODP). Keynote and Numbers files are refused with 415 upload/unsupported-type.

Metadata is a list of {id, value} items, such as Metadata: []calmlens.MetadataItem{{ID: "campaign.id", Value: "launch-2026"}}. The value can be any JSON value. To filter or group assets by an item in the portal, use the ID of a metadata field defined there; see Asset metadata.

Upload presets

Pass UploadPresetID on SubmitAssetOptions to apply an upload preset's folder, visibility, file types and size limit. To let a browser upload through a preset that requires tokens, sign a single-use token on your server with client.UploadTokens.Sign(ctx, calmlens.SignUploadTokenOptions{...}). Signing happens locally with your API key and makes no request.

CDN methods

Fetch retained content directly from your backend with client.CDN.Serve:

package main

import (
    "context"
    "fmt"
    "log"
    "io"
    calmlens "github.com/CalmLens/sdks/go"
)

func example(client *calmlens.ServerClient) {
    ctx := context.Background()
    response, err := client.CDN.Serve(ctx, calmlens.CDNServeOptions{CDNAssetURLOptions: calmlens.CDNAssetURLOptions{AssetID: "asset_5Gm2Rk8XqT3wLp9VbN4c", Resource: calmlens.ResourceOriginal}})
    if err != nil { log.Fatal(err) }
    defer response.Body.Close()
    if response.StatusCode < 200 || response.StatusCode >= 300 { log.Fatalf("CDN returned HTTP %d", response.StatusCode) }
    content, err := io.ReadAll(response.Body)
    if err != nil { log.Fatal(err) }
    fmt.Println(len(content))
}

The response contains raw content bytes, not the asset report. Check the response status before using the body, and close response.Body; the body is streamed. For text assets (such as comments sent with Text.Classify), decode the body as text. Options.Timeout covers a CDN.Serve download only until its headers arrive. The request uses your server API key; private reads require Download assets permission. For private content in browsers, sign the asset URL with CDN.SignAssetURL (see Signed asset URLs).

Upload with ProcessingOptions: &calmlens.ProcessingOptions{KeepContentAfterProcessing: calmlens.Ptr(true)} to retain content. The CDN delivers by the current classification.moderation.status, and still requires available content and authorised access. See Delivery while moderation runs.

Methods

Each method takes a context.Context (except CDN.GetAssetURL and the iterators) and the options type shown. See Calling conventions for defaults and return values.

MethodPurpose
Text.Classify(ctx, ClassifyTextOptions)Classify text and wait for the decision.
Assets.Create(ctx, SubmitAssetOptions)Upload content and queue processing.
Assets.Classify(ctx, SubmitAssetOptions)Upload content and wait for the decision where supported.
Assets.UploadPart(ctx, UploadAssetPartOptions)Send the next part of a multipart upload.
Assets.Retrieve(ctx, AssetIDOptions)Fetch one asset.
Assets.WaitForDecision(ctx, WaitForDecisionOptions)Retrieve an asset until it is completed or failed; see Waiting for a decision.
Assets.ListTimeline(ctx, ListAssetTimelineOptions) / Assets.ListTimelineAll(ListAssetTimelineOptions)Page through an audio or video asset's findings timeline Preview, in time order, or iterate over every segment.
Assets.List(ctx, ListAssetsOptions) / Assets.ListAll(ListAssetsOptions)List one page of assets, or iterate over every matching asset.
Assets.Search(ctx, SearchAssetsOptions)Search assets by keyword or meaning; see Asset search.
Assets.ListChildren(ctx, ListAssetChildrenOptions) / Assets.ListChildrenAll(ListAssetChildrenOptions)List an asset's extracted children.
Assets.Update(ctx, UpdateAssetOptions)Update asset fields.
Assets.Move(ctx, MoveAssetOptions)Move an asset to a folder, or to the project root with FolderID: nil.
Assets.Retry(ctx, AssetIDOptions)Retry an eligible processing failure.
Assets.Decide(ctx, DecideAssetOptions)Record a reviewer's Decision (allowed, limited, age-restricted, blocked or purged) with a required Note. An asset pending moderation can only be blocked or purged, and purging needs ConfirmPurge: true; see POST /assets/:assetId/decision.
Assets.Explain(ctx, ExplainAssetOptions)Fetch the full policy evidence for a decision (which rules and findings produced it), or with Rerun moderate the asset again under the current policy.
Assets.RemoveContent(ctx, AssetIDOptions)Remove stored content and keep the asset record and report.
Assets.Delete(ctx, AssetIDOptions)Delete the asset record and its content.
Assets.Batch(ctx, BatchAssetsOptions)Delete up to 500 assets (calmlens.AssetBatchOperationDelete) or remove their stored content (calmlens.AssetBatchOperationRemoveContent) in one queued request; see POST /projects/:projectId/assets/batch.
Folders.List, Folders.ListAll, Folders.Retrieve, Folders.Create, Folders.Update, Folders.Move, Folders.DeleteManage folders, with ListFoldersOptions, FolderIDOptions, CreateFolderOptions, UpdateFolderOptions and MoveFolderOptions. Use calmlens.ListFoldersOptions{} for the first 50 folders at the project root, sorted by name.
HashLists.List, HashLists.ListAll, HashLists.Retrieve, HashLists.Create, HashLists.Update, HashLists.DeleteManage hash lists that image uploads are compared with, with ListHashListsOptions, HashListIDOptions, CreateHashListOptions and UpdateHashListOptions.
HashLists.ListEntries, HashLists.ListEntriesAll, HashLists.AddEntry, HashLists.RemoveEntryManage the hashes in a hash list, with ListHashListEntriesOptions, AddHashListEntryOptions and HashListEntryIDOptions.
Policies.List, Policies.ListAll, Policies.Retrieve, Policies.Create, Policies.Update, Policies.Reset, Policies.Upgrade, Policies.SetAutomaticUpdates, Policies.DeleteManage the API key's organisation's moderation policies, with ListPoliciesOptions, PolicyIDOptions, CreatePolicyOptions, UpdatePolicyOptions, ResetPolicyOptions, UpgradePolicyOptions and SetPolicyAutomaticUpdatesOptions; see Policies.
Policies.RetrieveAssigned(ctx) / Policies.Assign(ctx, AssignPolicyOptions)Read or choose the policy the project moderates with.
Events.List(ctx, ListEventsOptions) / Events.ListAll(ListEventsOptions)Read one page of the project event feed, or iterate over its events.
EnsureLens(ctx, EnsureLensOptions) / EnsureLenses(ctx, EnsureLensesOptions)Create lenses, or change them to the definitions sent, by identifier.
Lenses.List, Lenses.ListAll, Lenses.Create, Lenses.Retrieve, Lenses.Update, Lenses.DeleteManage the project's lenses one by one, with ListLensesOptions, CreateLensOptions, LensIDOptions and UpdateLensOptions; see Lenses.
CDN.GetAssetURL(CDNAssetURLOptions) / CDN.Serve(ctx, CDNServeOptions)Build a CDN URL, or stream content.
CDN.SignAssetURL(ctx, SignAssetURLOptions)Sign a private asset's URL.
CDN.GetAssetInfo(ctx, url, GetAssetInfoOptions)Read an asset URL's display info.
UploadTokens.Sign(ctx, SignUploadTokenOptions)Sign an upload token locally, without a request.

Use calmlens.Ptr(value) for optional scalars. Updates send only the fields you set: a nil Name and a zero calmlens.Patch stay unchanged, calmlens.Set(value) changes a field and calmlens.Null[T]() clears it, for example Description: calmlens.Null[string](), Tags: calmlens.Set([]string{"reviewed"}).

Pagination

Every list returns a cursor page with Items, NextCursor and HasMore: pass NextCursor as Cursor while HasMore is true. Lists that can be sorted take Sort, a comma-separated list of fields, each descending when prefixed with -, such as "-createdAt,id"; see Pagination. Each list's ListAll method (Assets.ListChildrenAll, Assets.ListTimelineAll and HashLists.ListEntriesAll for the nested lists) returns an iterator that keeps the options and fetches pages as you go:

it := client.Assets.ListAll(calmlens.ListAssetsOptions{PageSize: 100})
for it.Next(ctx) {
	fmt.Println(it.Asset().ID)
}
if err := it.Err(); err != nil {
	log.Fatal(err)
}

The asset iterators return it.Asset(), and the others a *calmlens.Iterator[T] whose it.Item() is the current folder, hash list, entry, policy, lens or timeline segment. On Go 1.23 or later, for asset, err := range it.All(ctx) works too. For events, pass a saved cursor as ListEventsOptions{Cursor: saved}, and store it.Cursor() afterwards, even after an error; NextPage and Page read the feed a page at a time. An events page's NextCursor is never empty, and without Cursor the first page is empty and its NextCursor marks the current time. If a page says more follow but returns a cursor the iteration has already used, the iterator stops with sdk/invalid-response (the cursor is in Details["cursor"]) instead of repeating pages. See Reading the feed for cursor handling.

Errors and retries

Every failure is a *calmlens.Error, including invalid arguments and encoding failures. It carries Code, Status, RequestID (the X-Request-Id header, or the error body's requestId without it), Header, RetryAfter (a *time.Duration, nil without a Retry-After header), Details (the API's details object, such as validation issues; nil for connection failures) and Cause, and Error() includes the code, status and request ID.

Compare codes with the generated constants, such as calmlens.CodeAssetNotFound, or use calmlens.IsNotFound(err), calmlens.IsRetryable(err) and calmlens.ErrorCode(err). The original error stays in Cause, so errors.Is and errors.As still work.

CodeUsed for
sdk/transport-errorConnection, TLS, protocol, decompression and truncated-body failures
sdk/timeoutTimeouts
sdk/cancelledContext cancellation
sdk/invalid-argumentArguments rejected before a request
sdk/invalid-configInvalid client options
FailureWhat the SDK doesWhat you do
Connection failure or timeoutRetries reads (GET) and uploads (Create, Classify, Text.Classify, UploadPart) up to Options.MaxRetries times (default 2) with jittered backoffOnce retries run out, retry later: calmlens.IsRetryable(err) is true
429, 500, 502, 503, 504 or 409 idempotency/request-in-progressRetries the same requests, waiting for Retry-After (seconds or an HTTP date; 0 retries at once) when the API sends oneA Retry-After over a minute is returned to you instead: wait, then retry
Context cancelledStops with sdk/cancelled; never retriedNothing
Failure of another write, such as Assets.Update or Assets.DeleteNever retried automaticallyRetry only when repeating the change is safe
Upload from a stream that can't be rewoundSent onceUpload again from the start
Upload retried after a restartEach call sends a new Idempotency-Key, reused for its own retriesSet the same IdempotencyKey
RedirectNot followed; fails with sdk/http-error and the redirect's statusCheck BaseURL and CDNBaseURL
CDN.Serve failureRetries the same failures. Once retries run out, returns the last error response rather than an error; a connection failure or timeout still returns an errorCheck the response status

Set MaxRetries: calmlens.Ptr(0) to turn retries off. See Retrying requests safely.

SettingDefaultLimits
Options.Timeout120 secondsEach attempt of an API call, including text uploads
Options.UploadTimeoutNoneEach attempt of a binary upload
Options.MaxResponseBytes32 MiBThe API response body the client reads; CDN.Serve bodies aren't capped
Options.PartSizeBytes8 MiBContent larger than this is uploaded in parts of this size, from 5 MiB to 64 MiB
Options.ConnectTimeout10 secondsConnecting, when you don't set Options.HTTPClient
Options.ResponseHeaderTimeout120 secondsWaiting for response headers, when you don't set Options.HTTPClient

Use client.WithRequestOptions(calmlens.RequestOptions{...}) for a client with other retries or deadlines that shares the same credentials and lens cache. Requests send User-Agent: calmlens-go/<version> (go/<Go version>), and API requests Accept: application/json.

Webhooks

Verify the exact raw webhook bytes and the signature and timestamp headers before parsing JSON. Timestamps more than 5 minutes from now are rejected. With net/http, chi or any router that passes the *http.Request, VerifyWebhookRequest reads the body (up to 1 MiB), verifies it and returns the event:

func handleWebhook(w http.ResponseWriter, r *http.Request) {
	event, err := calmlens.VerifyWebhookRequest(r, os.Getenv("CALMLENS_WEBHOOK_SECRET"))
	if err != nil {
		http.Error(w, "Invalid webhook", http.StatusUnauthorized)
		return
	}
	log.Printf("Received event %s (%s)", event.ID, event.Type)
	// Deduplicate by event.ID, queue the work, then respond quickly.
	w.WriteHeader(http.StatusNoContent)
}

Call it before any middleware reads or decodes the body. With gin, pass c.Request before binding. Header names match in any case, and repeated signature headers are joined into one list. If you already hold the raw bytes:

  • calmlens.ParseWebhookEvent(rawBody, signature, timestamp, secret) verifies and decodes them.
  • calmlens.VerifyWebhookHeaders(rawBody, header, secret) verifies them against an http.Header.
  • calmlens.VerifyWebhookSignature(rawBody, signature, timestamp, secret) returns a boolean.

calmlens.WithTolerance (zero accepts only the signing second), calmlens.WithNow and calmlens.WithMaxBodyBytes change the defaults.

A webhook body is an event in the same shape Events.List returns, so the handler receives a *calmlens.Event with Type, Severity, Title, Description, AssetID, Asset and Facts. A verified body that is not a CalmLens event fails with sdk/invalid-webhook-payload. The parsed event keeps every field of the body in Raw, including fields added after your SDK version, calmlens.GetEventFact(event, key) returns one fact's value (nil when the event doesn't carry it) and calmlens.GetEventFacts(event) all of them by key, and event.Facts.IsTest() tells a test send from the portal or CLI apart from a real event. calmlens.WebhookDeliveryHeader (x-calmlens-delivery) identifies a delivery and stays the same across its retries; a redelivery gets a new one, so deduplicate on the event id. See Webhooks.

Command-line tool

See Local development to install the CLI, forward signed events and trigger test uploads.

Testing

Use the calmlenstest package for offline tests. See Go testing.

Last updated

Signing in

Signing out

Cookies on CalmLens

We use essential cookies for sign-in and security. With your permission, functional cookies remember your preferences and Google Analytics measures website use and signups. Optional ad measurement cookies link Google ad clicks to signups. Personalised advertising stays off. Manage cookies