Skip to content

Go SDK for Sirv REST API

By , Head of Sirv StudioUpdated

Open this page in a new chat

Short answer

Sirv's official Go SDK wraps the Sirv REST API, so you can upload, download, search and manage files, metadata, spins and account statistics from your code. Install it with go get github.com/sirv/sirv-rest-api-go, then connect with the client ID and secret from your Sirv account's API settings. The SDK gets and refreshes the access token for you.

After reading this you will know

  • How to install the SDK and connect to your Sirv account
  • Which file, account, statistics and spin methods it offers
  • How to handle errors and limits

The official Go SDK provides an idiomatic Go interface for interacting with the Sirv REST API.

It handles authentication automatically with token refresh and provides iterator patterns for paginated results.

Resources:

Install the SDK using Go modules:

go get github.com/sirv/sirv-rest-api-go
  • Go 1.21 or higher
package main
import (
"fmt"
"log"
"github.com/sirv/sirv-rest-api-go"
)
func main() {
// Initialize the client
client, err := sirv.NewClient(sirv.ClientConfig{
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
})
if err != nil {
log.Fatal(err)
}
// Get account information
account, err := client.GetAccountInfo()
if err != nil {
log.Fatal(err)
}
fmt.Printf("Account: %s\n", account.Alias)
// List files in a directory
contents, err := client.ReadFolderContents("/")
if err != nil {
log.Fatal(err)
}
for _, file := range contents.Contents {
fmt.Println(file.Filename)
}
}

The SDK handles authentication automatically. When you make your first API call, it obtains an access token using your client credentials.

The token is automatically refreshed before it expires.

client, err := sirv.NewClient(sirv.ClientConfig{
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
AutoRefreshToken: true, // Default: automatically refresh before expiry
})
// Optional: Manually authenticate to verify credentials
err = client.Connect()
if err != nil {
log.Printf("Authentication failed: %v", err)
}
// Check if connected
if client.IsConnected() {
fmt.Println("Token is valid")
}
// Get current access token for external use
token := client.GetAccessToken()
OptionTypeDefaultDescription
ClientIDstringrequiredYour API client ID
ClientSecretstringrequiredYour API client secret
BaseURLstringhttps://api.sirv.comAPI endpoint
AutoRefreshTokenbooltrueAuto-refresh token before expiry
TokenRefreshBufferint60Seconds before expiry to refresh token
Timeouttime.Duration30sRequest timeout
MaxRetriesint3Retry failed requests
import "time"
client, err := sirv.NewClient(sirv.ClientConfig{
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
BaseURL: "https://api.sirv.com",
AutoRefreshToken: true,
TokenRefreshBuffer: 60,
Timeout: 30 * time.Second,
MaxRetries: 3,
})

Complete file management including upload, download, copy, rename, delete, and metadata operations.

CategoryMethods
File OperationsReadFolderContents(), GetFileInfo(), UploadFile(), UploadFileFromPath(), DownloadFile(), DownloadFileTo(), CopyFile(), RenameFile(), DeleteFile(), CreateFolder(), FetchURL()
MetadataGetFileMeta(), SetFileMeta(), GetFileTitle(), SetFileTitle(), GetFileTags(), AddFileTags(), RemoveFileTags()
Search & IterationSearchFiles(), IterateSearchResults(), IterateFolderContents()
// List folder contents
contents, err := client.ReadFolderContents("/images")
// Get file information
info, err := client.GetFileInfo("/images/photo.jpg")
// Upload a file from bytes
data := []byte("file contents")
err = client.UploadFile("/images/photo.jpg", data)
// Upload a file from path
err = client.UploadFileFromPath("/images/photo.jpg", "/local/path/photo.jpg")
// Download a file to bytes
data, err := client.DownloadFile("/images/photo.jpg")
// Download a file to local path
err = client.DownloadFileTo("/images/photo.jpg", "/local/downloaded.jpg")
// Copy a file
err = client.CopyFile("/images/photo.jpg", "/backup/photo.jpg")
// Rename/move a file
err = client.RenameFile("/images/old-name.jpg", "/images/new-name.jpg")
// Delete a file
err = client.DeleteFile("/images/photo.jpg")
// Create a folder
err = client.CreateFolder("/images/new-folder")
// Fetch file from URL
err = client.FetchURL("https://example.com/image.jpg", "/images/fetched.jpg")
// Search files
results, err := client.SearchFiles(sirv.SearchParams{
Query: "filename:*.jpg",
From: "/images",
Size: 100,
})
// Iterate through search results (auto-pagination)
iter := client.IterateSearchResults(sirv.SearchParams{
Query: "extension:.jpg",
From: "/images",
})
for iter.Next() {
file := iter.Value()
fmt.Println(file.Filename)
}
if err := iter.Err(); err != nil {
log.Fatal(err)
}
// Iterate through folder contents (auto-pagination)
iter := client.IterateFolderContents("/images")
for iter.Next() {
item := iter.Value()
fmt.Println(item.Filename)
}
if err := iter.Err(); err != nil {
log.Fatal(err)
}
// Get and set file metadata
meta, err := client.GetFileMeta("/images/photo.jpg")
err = client.SetFileMeta("/images/photo.jpg", sirv.FileMeta{
Title: "My Photo",
Description: "A beautiful sunset",
})
// Get and set title
title, err := client.GetFileTitle("/images/photo.jpg")
err = client.SetFileTitle("/images/photo.jpg", "New Title")
// Manage tags
tags, err := client.GetFileTags("/images/photo.jpg")
err = client.AddFileTags("/images/photo.jpg", []string{"nature", "sunset", "beach"})
err = client.RemoveFileTags("/images/photo.jpg", []string{"beach"})

Manage your Sirv account settings and retrieve account information.

MethodDescription
GetAccountInfo()Get account information including CDN URL and account name
UpdateAccount()Update account settings (minify, fetching)
GetAccountLimits()Get API request limits and usage
GetStorageInfo()Get storage usage information
GetAccountUsers()List all account users
GetBillingPlan()Get billing plan details
SearchEvents()Search account events
// Get account information
account, err := client.GetAccountInfo()
fmt.Printf("CDN URL: %s\n", account.CDNURL)
// Get API limits
limits, err := client.GetAccountLimits()
fmt.Printf("API calls: %d/%d\n", limits.Used, limits.Limit)
// Get storage information
storage, err := client.GetStorageInfo()
fmt.Printf("Storage used: %d bytes\n", storage.Used)
// Get billing plan
plan, err := client.GetBillingPlan()
fmt.Printf("Plan: %s\n", plan.Name)
// List account users
users, err := client.GetAccountUsers()
// Search account events
events, err := client.SearchEvents(sirv.EventSearchParams{
Module: "files",
Level: "error",
})

Retrieve usage statistics for your account.

MethodDescription
GetHTTPStats()Get HTTP transfer statistics
GetSpinViewsStats()Get spin viewer statistics (max 5 days)
GetStorageStats()Get storage statistics
import "time"
// HTTP transfer statistics
from := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
to := time.Date(2024, 1, 31, 0, 0, 0, 0, time.UTC)
httpStats, err := client.GetHTTPStats(from, to)
// Spin views statistics (max 5 days)
spinFrom := time.Date(2024, 1, 1, 0, 0, 0, 0, time.UTC)
spinTo := time.Date(2024, 1, 5, 0, 0, 0, 0, time.UTC)
spinStats, err := client.GetSpinViewsStats(spinFrom, spinTo, "account-alias")
// Storage statistics
storageStats, err := client.GetStorageStats(from, to)

Convert between spin and video formats, and export to marketplaces.

// Convert spin to video
video, err := client.Spin2Video(sirv.Spin2VideoParams{
Filename: "/spins/product.spin",
})
// Convert video to spin
spin, err := client.Video2Spin(sirv.Video2SpinParams{
Filename: "/videos/product.mp4",
})
// Export spin for marketplaces
err = client.ExportSpinToAmazon(sirv.SpinExportParams{
Filename: "/spins/product.spin",
})
err = client.ExportSpinToWalmart(sirv.SpinExportParams{
Filename: "/spins/product.spin",
})
err = client.ExportSpinToHomeDepot(sirv.SpinExportParams{
Filename: "/spins/product.spin",
})
err = client.ExportSpinToLowes(sirv.SpinExportParams{
Filename: "/spins/product.spin",
})
err = client.ExportSpinToGrainger(sirv.SpinExportParams{
Filename: "/spins/product.spin",
})

Generate protected access tokens for secure file access.

jwt, err := client.GenerateJWT(sirv.JWTParams{
Filename: "/images/private-photo.jpg",
ExpiresIn: 3600, // 1 hour
})
fmt.Printf("Protected URL: %s\n", jwt.URL)

The SDK provides a GetAPIError function to extract detailed API error information.

import "github.com/sirv/sirv-rest-api-go"
err := client.UploadFile("/images/photo.jpg", data)
if err != nil {
if apiErr := sirv.GetAPIError(err); apiErr != nil {
fmt.Printf("Status: %d\n", apiErr.StatusCode)
fmt.Printf("Error code: %s\n", apiErr.ErrorCode)
fmt.Printf("Message: %s\n", apiErr.Message)
} else {
fmt.Printf("Unexpected error: %v\n", err)
}
}
FieldDescription
StatusCodeHTTP status code
ErrorCodeSirv-specific error code
MessageError message

All methods support Go’s context for cancellation and timeouts:

import "context"
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Methods accept context as first parameter
account, err := client.GetAccountInfoWithContext(ctx)

If a request takes longer than the time you set, it is cancelled and returns an error.

Back to top