Go SDK for Sirv REST API
go get github.com/sirv/sirv-rest-api-go2. Copy your Client ID and Client secret from Account › Settings › API.3. Connectclient, err := sirv.NewClient(sirv.ClientConfig{
ClientID: "your-client-id",
ClientSecret: "your-client-secret",
}) No account yet? Create one freeShort 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:
Installation
Section titled “Installation”Install the SDK using Go modules:
go get github.com/sirv/sirv-rest-api-goRequirements
Section titled “Requirements”- Go 1.21 or higher
Quick Start
Section titled “Quick Start”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) }}Authentication
Section titled “Authentication”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 credentialserr = client.Connect()if err != nil { log.Printf("Authentication failed: %v", err)}
// Check if connectedif client.IsConnected() { fmt.Println("Token is valid")}
// Get current access token for external usetoken := client.GetAccessToken()Configuration Options
Section titled “Configuration Options”| Option | Type | Default | Description |
|---|---|---|---|
ClientID | string | required | Your API client ID |
ClientSecret | string | required | Your API client secret |
BaseURL | string | https://api.sirv.com | API endpoint |
AutoRefreshToken | bool | true | Auto-refresh token before expiry |
TokenRefreshBuffer | int | 60 | Seconds before expiry to refresh token |
Timeout | time.Duration | 30s | Request timeout |
MaxRetries | int | 3 | Retry 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,})Files API
Section titled “Files API”Complete file management including upload, download, copy, rename, delete, and metadata operations.
Available Methods
Section titled “Available Methods”| Category | Methods |
|---|---|
| File Operations | ReadFolderContents(), GetFileInfo(), UploadFile(), UploadFileFromPath(), DownloadFile(), DownloadFileTo(), CopyFile(), RenameFile(), DeleteFile(), CreateFolder(), FetchURL() |
| Metadata | GetFileMeta(), SetFileMeta(), GetFileTitle(), SetFileTitle(), GetFileTags(), AddFileTags(), RemoveFileTags() |
| Search & Iteration | SearchFiles(), IterateSearchResults(), IterateFolderContents() |
Basic Operations
Section titled “Basic Operations”// List folder contentscontents, err := client.ReadFolderContents("/images")
// Get file informationinfo, err := client.GetFileInfo("/images/photo.jpg")
// Upload a file from bytesdata := []byte("file contents")err = client.UploadFile("/images/photo.jpg", data)
// Upload a file from patherr = client.UploadFileFromPath("/images/photo.jpg", "/local/path/photo.jpg")
// Download a file to bytesdata, err := client.DownloadFile("/images/photo.jpg")
// Download a file to local patherr = client.DownloadFileTo("/images/photo.jpg", "/local/downloaded.jpg")
// Copy a fileerr = client.CopyFile("/images/photo.jpg", "/backup/photo.jpg")
// Rename/move a fileerr = client.RenameFile("/images/old-name.jpg", "/images/new-name.jpg")
// Delete a fileerr = client.DeleteFile("/images/photo.jpg")
// Create a foldererr = client.CreateFolder("/images/new-folder")
// Fetch file from URLerr = client.FetchURL("https://example.com/image.jpg", "/images/fetched.jpg")Search Files
Section titled “Search Files”// Search filesresults, 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)}Folder Iteration
Section titled “Folder Iteration”// 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)}Metadata Operations
Section titled “Metadata Operations”// Get and set file metadatameta, err := client.GetFileMeta("/images/photo.jpg")
err = client.SetFileMeta("/images/photo.jpg", sirv.FileMeta{ Title: "My Photo", Description: "A beautiful sunset",})
// Get and set titletitle, err := client.GetFileTitle("/images/photo.jpg")err = client.SetFileTitle("/images/photo.jpg", "New Title")
// Manage tagstags, err := client.GetFileTags("/images/photo.jpg")err = client.AddFileTags("/images/photo.jpg", []string{"nature", "sunset", "beach"})err = client.RemoveFileTags("/images/photo.jpg", []string{"beach"})Account API
Section titled “Account API”Manage your Sirv account settings and retrieve account information.
Available Methods
Section titled “Available Methods”| Method | Description |
|---|---|
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 |
Examples
Section titled “Examples”// Get account informationaccount, err := client.GetAccountInfo()fmt.Printf("CDN URL: %s\n", account.CDNURL)
// Get API limitslimits, err := client.GetAccountLimits()fmt.Printf("API calls: %d/%d\n", limits.Used, limits.Limit)
// Get storage informationstorage, err := client.GetStorageInfo()fmt.Printf("Storage used: %d bytes\n", storage.Used)
// Get billing planplan, err := client.GetBillingPlan()fmt.Printf("Plan: %s\n", plan.Name)
// List account usersusers, err := client.GetAccountUsers()
// Search account eventsevents, err := client.SearchEvents(sirv.EventSearchParams{ Module: "files", Level: "error",})Statistics API
Section titled “Statistics API”Retrieve usage statistics for your account.
| Method | Description |
|---|---|
GetHTTPStats() | Get HTTP transfer statistics |
GetSpinViewsStats() | Get spin viewer statistics (max 5 days) |
GetStorageStats() | Get storage statistics |
import "time"
// HTTP transfer statisticsfrom := 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 statisticsstorageStats, err := client.GetStorageStats(from, to)Spins & 360 Views
Section titled “Spins & 360 Views”Convert between spin and video formats, and export to marketplaces.
// Convert spin to videovideo, err := client.Spin2Video(sirv.Spin2VideoParams{ Filename: "/spins/product.spin",})
// Convert video to spinspin, err := client.Video2Spin(sirv.Video2SpinParams{ Filename: "/videos/product.mp4",})
// Export spin for marketplaceserr = 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",})JWT Generation
Section titled “JWT Generation”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)Error Handling
Section titled “Error Handling”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) }}API Error Fields
Section titled “API Error Fields”| Field | Description |
|---|---|
StatusCode | HTTP status code |
ErrorCode | Sirv-specific error code |
Message | Error message |
Context Support
Section titled “Context Support”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 parameteraccount, err := client.GetAccountInfoWithContext(ctx)If a request takes longer than the time you set, it is cancelled and returns an error.
