# Go SDK for Sirv REST API

The official Go SDK provides an idiomatic Go interface for interacting with the [Sirv REST API](/help/rest-api/reference/).

Using an AI coding agent?

Install the [`sirv-api`](https://www.skills.sh/sirv/image-optimization-skill/sirv-api) skill, and your agent can call the Sirv API for you. Ask in plain words, such as “Upload the photos in /shoots/spring and tag them by product.” [See all 8 skills](/help/rest-api/sirv-skills-for-ai-agents/)

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

**Resources:**

-   [GitHub Repository](https://github.com/sirv/sirv-rest-api-go)
-   [pkg.go.dev Documentation](https://pkg.go.dev/github.com/sirv/sirv-rest-api-go)
-   [API Documentation](/help/rest-api/reference/)

## Installation

Install the SDK using Go modules:

```bash
go get github.com/sirv/sirv-rest-api-go
```

### Requirements

-   Go 1.21 or higher

## Quick Start

```go
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

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.

Tip

Get your API credentials from [Settings > API access](https://app.sirv.com/settings/api) in your Sirv account.

```go
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()
```

### 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 |

```go
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

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

### 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

```go
// 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

```go
// 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)
}
```

### Folder Iteration

```go
// 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

```go
// 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"})
```

## Account API

Manage your Sirv account settings and retrieve account information.

### Available Methods

| Method | Description |
| --- | --- |
| `GetAccountInfo()` | Get account information including CDN URL and [account name](/help/getting-started/account-name-subdomain/) |
| `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

```go
// 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",
})
```

## 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 |

```go
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)
```

## Spins & 360 Views

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

```go
// 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",
})
```

## JWT Generation

Generate protected access tokens for secure file access.

```go
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

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

```go
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

| Field | Description |
| --- | --- |
| `StatusCode` | HTTP status code |
| `ErrorCode` | Sirv-specific error code |
| `Message` | Error message |

## Context Support

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

```go
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.
