sirv

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 27, 2026 License: MIT Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Sirv REST API Go SDK

Official Go SDK for the Sirv REST API. Provides a simple, type-safe way to interact with Sirv's image hosting and processing platform.

Features

  • Complete coverage of all 40+ Sirv REST API endpoints
  • Automatic token management with configurable expiry
  • Context support for cancellation and timeouts
  • Retry logic with exponential backoff
  • Thread-safe client
  • Iterator patterns for paginated results
  • Comprehensive type definitions

Installation

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

Requirements

  • Go 1.21 or later

Quick Start

package main

import (
    "context"
    "fmt"
    "log"

    sirv "github.com/sirv/sirv-rest-api-go"
)

func main() {
    // Create client
    client, err := sirv.NewClient(sirv.ClientConfig{
        ClientID:     "your-client-id",
        ClientSecret: "your-client-secret",
    })
    if err != nil {
        log.Fatal(err)
    }

    ctx := context.Background()

    // Connect (authenticate)
    token, err := client.Connect(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Connected! Token expires in %d seconds\n", token.ExpiresIn)

    // Get account info
    account, err := client.GetAccountInfo(ctx)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Account: %s\n", account.Alias)
    fmt.Printf("CDN URL: %s\n", account.CdnURL)

    // List folder contents
    folder, err := client.ReadFolderContents(ctx, "/", "")
    if err != nil {
        log.Fatal(err)
    }
    for _, item := range folder.Contents {
        if item.IsDirectory {
            fmt.Printf("[DIR]  %s\n", item.Filename)
        } else {
            fmt.Printf("[FILE] %s\n", item.Filename)
        }
    }
}

Configuration

client, err := sirv.NewClient(sirv.ClientConfig{
    // Required
    ClientID:     "your-client-id",
    ClientSecret: "your-client-secret",

    // Optional
    BaseURL:            "https://api.sirv.com", // Default
    AutoRefreshToken:   sirv.BoolPtr(true),     // Default: true
    TokenRefreshBuffer: 60,                      // Seconds before expiry to refresh (default: 60)
    Timeout:            30 * time.Second,        // Request timeout (default: 30s)
    MaxRetries:         3,                       // Max retries on 5xx errors (default: 3)
})

Custom Token Expiry

You can customize how long the token is valid (5-604800 seconds):

// Request a token valid for 1 hour (3600 seconds)
token, err := client.Connect(ctx, 3600)

// Request a token valid for 7 days (604800 seconds)
token, err := client.Connect(ctx, 604800)

API Reference

Authentication
// Connect and get token
token, err := client.Connect(ctx)
token, err := client.Connect(ctx, 3600) // With custom expiry

// Check connection status
isConnected := client.IsConnected()

// Get current token
token := client.GetAccessToken()
Account Operations
// Get account info
account, err := client.GetAccountInfo(ctx)

// Update account settings
err := client.UpdateAccount(ctx, &sirv.AccountUpdateOptions{
    Minify: &sirv.MinifyOptions{Enabled: sirv.BoolPtr(true)},
})

// Get rate limits
limits, err := client.GetAccountLimits(ctx)

// Get storage info
storage, err := client.GetStorageInfo(ctx)

// Get billing plan
plan, err := client.GetBillingPlan(ctx)

// Get account users
users, err := client.GetAccountUsers(ctx)

// Search events
events, err := client.SearchEvents(ctx, &sirv.EventSearchParams{
    Level: "error",
    From:  "2024-01-01",
})
File Operations
// Get file info
info, err := client.GetFileInfo(ctx, "/path/to/file.jpg")

// Read folder contents
folder, err := client.ReadFolderContents(ctx, "/my-folder", "")

// Iterate folder (handles pagination)
fileCh, errCh := client.IterateFolderContents(ctx, "/my-folder")
for file := range fileCh {
    fmt.Println(file.Filename)
}
if err := <-errCh; err != nil {
    log.Fatal(err)
}

// Search files
results, err := client.SearchFiles(ctx, &sirv.SearchParams{
    Query: "*.jpg",
    Size:  sirv.IntPtr(10),
})

// Iterate search results (handles pagination)
fileCh, errCh := client.IterateSearchResults(ctx, &sirv.SearchParams{Query: "*"})
for file := range fileCh {
    fmt.Println(file.Filename)
}

// Upload file from bytes
err := client.UploadFile(ctx, "/path/to/dest.jpg", imageBytes, nil)

// Upload file from local path
err := client.UploadFileFromPath(ctx, "/path/to/dest.jpg", "./local-file.jpg", nil)

// Download file
data, err := client.DownloadFile(ctx, "/path/to/file.jpg")

// Download file to local path
err := client.DownloadFileTo(ctx, "/path/to/file.jpg", "./local-file.jpg")

// Create folder
err := client.CreateFolder(ctx, "/new-folder")

// Delete file
err := client.DeleteFile(ctx, "/path/to/file.jpg")

// Copy file
err := client.CopyFile(ctx, &sirv.CopyParams{From: "/source.jpg", To: "/dest.jpg"})

// Rename/move file
err := client.RenameFile(ctx, &sirv.RenameParams{From: "/old.jpg", To: "/new.jpg"})

// Fetch from URL
err := client.FetchURL(ctx, &sirv.FetchURLParams{
    URL:      "https://example.com/image.jpg",
    Filename: "/fetched/image.jpg",
})
Metadata Operations
// Get file metadata
meta, err := client.GetFileMeta(ctx, "/path/to/file.jpg")

// Set file metadata
err := client.SetFileMeta(ctx, "/path/to/file.jpg", &sirv.FileMeta{
    Title:       "My Image",
    Description: "A beautiful image",
    Tags:        []string{"nature", "landscape"},
})

// Get/set individual metadata fields
title, err := client.GetFileTitle(ctx, "/path/to/file.jpg")
err := client.SetFileTitle(ctx, "/path/to/file.jpg", "New Title")

tags, err := client.GetFileTags(ctx, "/path/to/file.jpg")
err := client.AddFileTags(ctx, "/path/to/file.jpg", []string{"tag1", "tag2"})
err := client.RemoveFileTags(ctx, "/path/to/file.jpg", []string{"tag1"})

// Product metadata
product, err := client.GetProductMeta(ctx, "/path/to/file.jpg")
err := client.SetProductMeta(ctx, "/path/to/file.jpg", &sirv.ProductMeta{
    Name:  "Product Name",
    SKU:   "SKU-123",
    Brand: "Brand Name",
})

// Approval flag
approved, err := client.GetApprovalFlag(ctx, "/path/to/file.jpg")
err := client.SetApprovalFlag(ctx, "/path/to/file.jpg", true)
JWT Protected URLs
jwt, err := client.GenerateJWT(ctx, &sirv.JWTParams{
    Filename:  "/protected/image.jpg",
    ExpiresIn: sirv.IntPtr(3600), // 1 hour
})
fmt.Printf("Protected URL: %s\n", jwt.URL)
Spins/360 Operations
// Convert spin to video
videoFile, err := client.Spin2Video(ctx, &sirv.SpinConvertParams{
    Filename: "/spin/product.spin",
    Options: &sirv.SpinConvertOptions{
        Width:  sirv.IntPtr(800),
        Height: sirv.IntPtr(600),
    },
})

// Convert video to spin
spinFile, err := client.Video2Spin(ctx, &sirv.Video2SpinParams{
    Filename: "/video/product.mp4",
})

// Export spin to marketplaces
err := client.ExportSpinToAmazon(ctx, &sirv.ExportSpinParams{
    Filename: "/spin/product.spin",
    ASIN:     "B01234567",
})
Statistics
// HTTP transfer stats
httpStats, err := client.GetHTTPStats(ctx, &sirv.StatsParams{
    From: "2024-01-01",
    To:   "2024-01-31",
})

// Spin views stats (max 5-day range)
spinStats, err := client.GetSpinViewsStats(ctx, &sirv.StatsParams{
    From: "2024-01-01",
    To:   "2024-01-05",
})

// Storage stats
storageStats, err := client.GetStorageStats(ctx, &sirv.StatsParams{
    From: "2024-01-01",
    To:   "2024-01-31",
})

Error Handling

account, err := client.GetAccountInfo(ctx)
if err != nil {
    if apiErr := sirv.GetAPIError(err); apiErr != nil {
        fmt.Printf("API Error: %s (status %d)\n", apiErr.Message, apiErr.StatusCode)
    } else {
        fmt.Printf("Error: %v\n", err)
    }
}

Context Support

All API methods accept a context for cancellation and timeout control:

// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

account, err := client.GetAccountInfo(ctx)

// With cancellation
ctx, cancel := context.WithCancel(context.Background())
go func() {
    // Cancel after some condition
    cancel()
}()

Thread Safety

The Client is thread-safe and can be used concurrently from multiple goroutines:

var wg sync.WaitGroup
for i := 0; i < 10; i++ {
    wg.Add(1)
    go func(i int) {
        defer wg.Done()
        info, err := client.GetFileInfo(ctx, fmt.Sprintf("/file%d.jpg", i))
        // ...
    }(i)
}
wg.Wait()

License

MIT License - see LICENSE for details.

Documentation

Overview

Package sirv provides a Go SDK for the Sirv REST API.

Example usage:

client := sirv.NewClient(sirv.ClientConfig{
	ClientID:     "your-client-id",
	ClientSecret: "your-client-secret",
})

ctx := context.Background()
token, err := client.Connect(ctx)
if err != nil {
	log.Fatal(err)
}

account, err := client.GetAccountInfo(ctx)
if err != nil {
	log.Fatal(err)
}
fmt.Println("CDN URL:", account.CdnURL)

Package sirv provides a Go SDK for the Sirv REST API.

Package sirv provides a Go SDK for the Sirv REST API.

Index

Constants

View Source
const (
	// DefaultBaseURL is the default Sirv API base URL.
	DefaultBaseURL = "https://api.sirv.com"
	// DefaultTokenRefreshBuffer is the default seconds before token expiry to trigger refresh.
	DefaultTokenRefreshBuffer = 60
	// DefaultTimeout is the default HTTP request timeout.
	DefaultTimeout = 30 * time.Second
	// DefaultMaxRetries is the default maximum number of retries for failed requests.
	DefaultMaxRetries = 3
)

Variables

This section is empty.

Functions

func BoolPtr

func BoolPtr(b bool) *bool

Helper function to create bool pointer

func Float64Ptr

func Float64Ptr(f float64) *float64

Helper function to create float64 pointer

func Int64Ptr

func Int64Ptr(i int64) *int64

Helper function to create int64 pointer

func IntPtr

func IntPtr(i int) *int

Helper function to create int pointer

func IsAPIError

func IsAPIError(err error) bool

IsAPIError checks if an error is an APIError.

func StringPtr

func StringPtr(s string) *string

Helper function to create string pointer

func Version

func Version() string

Version returns the SDK version.

Types

type APIError

type APIError struct {
	StatusCode int    `json:"statusCode"`
	ErrorCode  string `json:"error,omitempty"`
	Message    string `json:"message"`
}

APIError represents an error returned by the Sirv API.

func GetAPIError

func GetAPIError(err error) *APIError

GetAPIError returns the APIError if err is one, otherwise nil.

func NewAPIError

func NewAPIError(statusCode int, message string, errorCode string) *APIError

NewAPIError creates a new API error.

func (*APIError) Error

func (e *APIError) Error() string

Error implements the error interface.

type AccountEvent

type AccountEvent struct {
	ID        string `json:"id"`
	Module    string `json:"module"`
	Type      string `json:"type"`
	Level     string `json:"level"`
	Message   string `json:"message"`
	Filename  string `json:"filename,omitempty"`
	Timestamp string `json:"timestamp"`
	Seen      *bool  `json:"seen,omitempty"`
}

AccountEvent represents an account event log entry.

type AccountInfo

type AccountInfo struct {
	Alias         string                  `json:"alias"`
	CdnURL        string                  `json:"cdnURL"`
	DateCreated   string                  `json:"dateCreated,omitempty"`
	Fetching      *FetchingOptions        `json:"fetching,omitempty"`
	Minify        *MinifyOptions          `json:"minify,omitempty"`
	Aliases       map[string]*AliasConfig `json:"aliases,omitempty"`
	FileSizeLimit int64                   `json:"fileSizeLimit,omitempty"`
}

AccountInfo represents account information.

type AccountLimits

type AccountLimits struct {
	S3   *RateLimitInfo `json:"s3,omitempty"`
	Rest *RateLimitInfo `json:"rest,omitempty"`
	FTP  *RateLimitInfo `json:"ftp,omitempty"`
}

AccountLimits represents API rate limits for different endpoint types.

type AccountUpdateOptions

type AccountUpdateOptions struct {
	Fetching *FetchingOptions `json:"fetching,omitempty"`
	Minify   *MinifyOptions   `json:"minify,omitempty"`
	Aliases  []string         `json:"aliases,omitempty"`
}

AccountUpdateOptions represents options for updating account settings.

type AccountUser

type AccountUser struct {
	UserID      string `json:"userId"`
	Email       string `json:"email"`
	FirstName   string `json:"firstName,omitempty"`
	LastName    string `json:"lastName,omitempty"`
	Role        string `json:"role"`
	DateCreated string `json:"dateCreated,omitempty"`
}

AccountUser represents account user information.

type AliasConfig

type AliasConfig struct {
	Prefix       string `json:"prefix,omitempty"`
	Cdn          *bool  `json:"cdn,omitempty"`
	CustomDomain string `json:"customDomain,omitempty"`
}

AliasConfig represents alias configuration.

type BatchDeleteItemResult

type BatchDeleteItemResult struct {
	Filename string `json:"filename"`
	Success  bool   `json:"success"`
	Error    string `json:"error,omitempty"`
}

BatchDeleteItemResult represents result for a single file in batch delete.

type BatchDeleteResult

type BatchDeleteResult struct {
	JobID   string                  `json:"jobId,omitempty"`
	Status  string                  `json:"status,omitempty"`
	Results []BatchDeleteItemResult `json:"results,omitempty"`
}

BatchDeleteResult represents batch delete operation result.

type BatchZipParams

type BatchZipParams struct {
	Filenames []string `json:"filenames"`
	Filename  string   `json:"filename"`
}

BatchZipParams represents batch ZIP operation parameters.

type BatchZipResult

type BatchZipResult struct {
	JobID    string `json:"jobId,omitempty"`
	Status   string `json:"status,omitempty"`
	Filename string `json:"filename,omitempty"`
}

BatchZipResult represents batch ZIP operation result.

type BillingPlan

type BillingPlan struct {
	ID                string     `json:"id,omitempty"`
	Name              string     `json:"name"`
	Description       string     `json:"description,omitempty"`
	Period            string     `json:"period,omitempty"`
	Storage           int64      `json:"storage"`
	DataTransferLimit *int64     `json:"dataTransferLimit,omitempty"`
	Price             *PlanPrice `json:"price,omitempty"`
	DateActive        string     `json:"dateActive,omitempty"`
}

BillingPlan represents billing plan information.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client is the Sirv REST API client.

func NewClient

func NewClient(config ClientConfig) (*Client, error)

NewClient creates a new Sirv API client.

func (*Client) AddFileTags

func (c *Client) AddFileTags(ctx context.Context, filename string, tags []string) error

AddFileTags adds tags to file.

func (*Client) BatchDelete

func (c *Client) BatchDelete(ctx context.Context, filenames []string) (*BatchDeleteResult, error)

BatchDelete deletes multiple files/folders.

func (*Client) BatchZip

func (c *Client) BatchZip(ctx context.Context, params *BatchZipParams) (*BatchZipResult, error)

BatchZip creates ZIP archive from multiple files.

func (*Client) Connect

func (c *Client) Connect(ctx context.Context, expiresIn ...int) (*TokenResponse, error)

Connect authenticates and obtains a bearer token. expiresIn is optional - pass nil for default (1200 seconds/20 minutes). Valid range is 5-604800 seconds.

func (*Client) CopyFile

func (c *Client) CopyFile(ctx context.Context, params *CopyParams) error

CopyFile copies a file.

func (*Client) CreateFolder

func (c *Client) CreateFolder(ctx context.Context, dirname string) error

CreateFolder creates a new folder.

func (*Client) DeleteFile

func (c *Client) DeleteFile(ctx context.Context, filename string) error

DeleteFile deletes a file or empty folder.

func (*Client) DeletePointOfInterest

func (c *Client) DeletePointOfInterest(ctx context.Context, filename, name string) error

DeletePointOfInterest deletes point of interest.

func (*Client) DownloadFile

func (c *Client) DownloadFile(ctx context.Context, filename string) ([]byte, error)

DownloadFile downloads a file and returns its content as bytes.

func (*Client) DownloadFileTo

func (c *Client) DownloadFileTo(ctx context.Context, filename, localPath string) error

DownloadFileTo downloads a file to a local path.

func (*Client) ExportSpinToAmazon

func (c *Client) ExportSpinToAmazon(ctx context.Context, params *ExportSpinParams) error

ExportSpinToAmazon exports spin to Amazon.

func (*Client) ExportSpinToGrainger

func (c *Client) ExportSpinToGrainger(ctx context.Context, params *ExportSpinParams) error

ExportSpinToGrainger exports spin to Grainger.

func (*Client) ExportSpinToHomeDepot

func (c *Client) ExportSpinToHomeDepot(ctx context.Context, params *ExportSpinParams) error

ExportSpinToHomeDepot exports spin to Home Depot.

func (*Client) ExportSpinToLowes

func (c *Client) ExportSpinToLowes(ctx context.Context, params *ExportSpinParams) error

ExportSpinToLowes exports spin to Lowe's.

func (*Client) ExportSpinToWalmart

func (c *Client) ExportSpinToWalmart(ctx context.Context, params *ExportSpinParams) error

ExportSpinToWalmart exports spin to Walmart.

func (*Client) FetchURL

func (c *Client) FetchURL(ctx context.Context, params *FetchURLParams) error

FetchURL fetches file from external URL.

func (*Client) GenerateJWT

func (c *Client) GenerateJWT(ctx context.Context, params *JWTParams) (*JWTResponse, error)

GenerateJWT generates JWT protected URL.

func (*Client) GetAccessToken

func (c *Client) GetAccessToken() string

GetAccessToken returns the current token (useful for external integrations).

func (*Client) GetAccountInfo

func (c *Client) GetAccountInfo(ctx context.Context) (*AccountInfo, error)

GetAccountInfo gets account information.

func (*Client) GetAccountLimits

func (c *Client) GetAccountLimits(ctx context.Context) (*AccountLimits, error)

GetAccountLimits gets API rate limits.

func (*Client) GetAccountUsers

func (c *Client) GetAccountUsers(ctx context.Context) ([]AccountUser, error)

GetAccountUsers gets all account users.

func (*Client) GetApprovalFlag

func (c *Client) GetApprovalFlag(ctx context.Context, filename string) (bool, error)

GetApprovalFlag gets approval flag.

func (*Client) GetBatchDeleteStatus

func (c *Client) GetBatchDeleteStatus(ctx context.Context, jobID string) (*BatchDeleteResult, error)

GetBatchDeleteStatus gets batch delete job status.

func (*Client) GetBillingPlan

func (c *Client) GetBillingPlan(ctx context.Context) (*BillingPlan, error)

GetBillingPlan gets billing plan details.

func (*Client) GetFileDescription

func (c *Client) GetFileDescription(ctx context.Context, filename string) (string, error)

GetFileDescription gets file description.

func (*Client) GetFileInfo

func (c *Client) GetFileInfo(ctx context.Context, filename string) (*FileInfo, error)

GetFileInfo gets file information.

func (*Client) GetFileMeta

func (c *Client) GetFileMeta(ctx context.Context, filename string) (*FileMeta, error)

GetFileMeta gets all file metadata.

func (*Client) GetFileTags

func (c *Client) GetFileTags(ctx context.Context, filename string) ([]string, error)

GetFileTags gets file tags.

func (*Client) GetFileTitle

func (c *Client) GetFileTitle(ctx context.Context, filename string) (string, error)

GetFileTitle gets file title.

func (*Client) GetFolderOptions

func (c *Client) GetFolderOptions(ctx context.Context, dirname string) (*FolderOptions, error)

GetFolderOptions gets folder options.

func (*Client) GetHTTPStats

func (c *Client) GetHTTPStats(ctx context.Context, params *StatsParams) ([]HTTPStats, error)

GetHTTPStats gets HTTP transfer statistics.

func (*Client) GetPointsOfInterest

func (c *Client) GetPointsOfInterest(ctx context.Context, filename string) ([]PointOfInterest, error)

GetPointsOfInterest gets points of interest for a file.

func (*Client) GetProductMeta

func (c *Client) GetProductMeta(ctx context.Context, filename string) (*ProductMeta, error)

GetProductMeta gets product metadata.

func (*Client) GetSpinViewsStats

func (c *Client) GetSpinViewsStats(ctx context.Context, params *StatsParams) ([]SpinViewStats, error)

GetSpinViewsStats gets spin views statistics (max 5-day range).

func (*Client) GetStorageInfo

func (c *Client) GetStorageInfo(ctx context.Context) (*StorageInfo, error)

GetStorageInfo gets storage usage information.

func (*Client) GetStorageStats

func (c *Client) GetStorageStats(ctx context.Context, params *StatsParams) ([]StorageStats, error)

GetStorageStats gets storage statistics.

func (*Client) GetUserInfo

func (c *Client) GetUserInfo(ctx context.Context, userID string) (*UserInfo, error)

GetUserInfo gets user information. userID is optional - pass empty string to get current user.

func (*Client) GetZipStatus

func (c *Client) GetZipStatus(ctx context.Context, jobID string) (*BatchZipResult, error)

GetZipStatus gets ZIP job status.

func (*Client) IsConnected

func (c *Client) IsConnected() bool

IsConnected checks if client is connected with a valid token.

func (*Client) IterateFolderContents

func (c *Client) IterateFolderContents(ctx context.Context, dirname string) (<-chan FileInfo, <-chan error)

IterateFolderContents iterates through all items in a folder (handles pagination automatically). Returns a channel that yields FileInfo items.

func (*Client) IterateSearchResults

func (c *Client) IterateSearchResults(ctx context.Context, params *SearchParams) (<-chan FileInfo, <-chan error)

IterateSearchResults iterates through all search results (handles pagination automatically). Returns a channel that yields FileInfo items.

func (*Client) MarkEventsSeen

func (c *Client) MarkEventsSeen(ctx context.Context, eventIDs []string) error

MarkEventsSeen marks events as seen.

func (*Client) ReadFolderContents

func (c *Client) ReadFolderContents(ctx context.Context, dirname string, continuation string) (*FolderContents, error)

ReadFolderContents reads folder contents.

func (*Client) RemoveFileTags

func (c *Client) RemoveFileTags(ctx context.Context, filename string, tags []string) error

RemoveFileTags removes tags from file.

func (*Client) RenameFile

func (c *Client) RenameFile(ctx context.Context, params *RenameParams) error

RenameFile renames or moves a file/folder.

func (*Client) ScrollSearch

func (c *Client) ScrollSearch(ctx context.Context, scrollID string) (*SearchResult, error)

ScrollSearch continues paginated search.

func (*Client) SearchEvents

func (c *Client) SearchEvents(ctx context.Context, params *EventSearchParams) ([]AccountEvent, error)

SearchEvents searches account events.

func (*Client) SearchFiles

func (c *Client) SearchFiles(ctx context.Context, params *SearchParams) (*SearchResult, error)

SearchFiles searches files.

func (*Client) SetApprovalFlag

func (c *Client) SetApprovalFlag(ctx context.Context, filename string, approved bool) error

SetApprovalFlag sets approval flag.

func (*Client) SetFileDescription

func (c *Client) SetFileDescription(ctx context.Context, filename, description string) error

SetFileDescription sets file description.

func (*Client) SetFileMeta

func (c *Client) SetFileMeta(ctx context.Context, filename string, meta *FileMeta) error

SetFileMeta sets file metadata.

func (*Client) SetFileTitle

func (c *Client) SetFileTitle(ctx context.Context, filename, title string) error

SetFileTitle sets file title.

func (*Client) SetFolderOptions

func (c *Client) SetFolderOptions(ctx context.Context, dirname string, options *FolderOptions) error

SetFolderOptions sets folder options.

func (*Client) SetPointOfInterest

func (c *Client) SetPointOfInterest(ctx context.Context, filename string, poi *PointOfInterest) error

SetPointOfInterest sets point of interest.

func (*Client) SetProductMeta

func (c *Client) SetProductMeta(ctx context.Context, filename string, meta *ProductMeta) error

SetProductMeta sets product metadata.

func (*Client) Spin2Video

func (c *Client) Spin2Video(ctx context.Context, params *SpinConvertParams) (string, error)

Spin2Video converts spin to video.

func (*Client) UpdateAccount

func (c *Client) UpdateAccount(ctx context.Context, options *AccountUpdateOptions) error

UpdateAccount updates account settings.

func (*Client) UploadFile

func (c *Client) UploadFile(ctx context.Context, targetPath string, content []byte, options *UploadOptions) error

UploadFile uploads a file from bytes.

func (*Client) UploadFileFromPath

func (c *Client) UploadFileFromPath(ctx context.Context, targetPath, localPath string, options *UploadOptions) error

UploadFileFromPath uploads a file from local path.

func (*Client) UploadFileFromReader

func (c *Client) UploadFileFromReader(ctx context.Context, targetPath string, reader io.Reader, options *UploadOptions) error

UploadFileFromReader uploads a file from io.Reader.

func (*Client) Video2Spin

func (c *Client) Video2Spin(ctx context.Context, params *Video2SpinParams) (string, error)

Video2Spin converts video to spin.

type ClientConfig

type ClientConfig struct {
	// ClientID is your Sirv API client ID (required).
	ClientID string
	// ClientSecret is your Sirv API client secret (required).
	ClientSecret string
	// BaseURL is the base URL for API (default: https://api.sirv.com).
	BaseURL string
	// AutoRefreshToken enables automatic token refresh before expiry (default: true).
	AutoRefreshToken *bool
	// TokenRefreshBuffer is seconds before token expiry to trigger refresh (default: 60).
	TokenRefreshBuffer int
	// Timeout is the request timeout (default: 30s).
	Timeout time.Duration
	// MaxRetries is the maximum number of retries for failed requests (default: 3).
	MaxRetries int
	// HTTPClient allows using a custom HTTP client.
	HTTPClient *http.Client
}

ClientConfig holds the configuration for the Sirv client.

type CopyParams

type CopyParams struct {
	From string `json:"from"`
	To   string `json:"to"`
}

CopyParams represents copy operation parameters.

type EventSearchParams

type EventSearchParams struct {
	Module   string `json:"module,omitempty"`
	Type     string `json:"type,omitempty"`
	Level    string `json:"level,omitempty"`
	Filename string `json:"filename,omitempty"`
	From     string `json:"from,omitempty"`
	To       string `json:"to,omitempty"`
}

EventSearchParams represents parameters for searching account events.

type ExportSpinParams

type ExportSpinParams struct {
	Filename  string `json:"filename"`
	ASIN      string `json:"asin,omitempty"`
	ProductID string `json:"productId,omitempty"`
}

ExportSpinParams represents spin export parameters.

type FetchURLParams

type FetchURLParams struct {
	URL      string `json:"url"`
	Filename string `json:"filename"`
	Wait     *bool  `json:"wait,omitempty"`
}

FetchURLParams represents parameters for fetching file from URL.

type FetchingOptions

type FetchingOptions struct {
	Enabled *bool               `json:"enabled,omitempty"`
	Type    string              `json:"type,omitempty"`
	HTTP    *HTTPFetchingConfig `json:"http,omitempty"`
}

FetchingOptions represents HTTP fetching configuration.

type FileInfo

type FileInfo struct {
	Filename    string    `json:"filename"`
	Dirname     string    `json:"dirname,omitempty"`
	Basename    string    `json:"basename,omitempty"`
	IsDirectory bool      `json:"isDirectory"`
	Size        *int64    `json:"size,omitempty"`
	Ctime       string    `json:"ctime,omitempty"`
	Mtime       string    `json:"mtime,omitempty"`
	ContentType string    `json:"contentType,omitempty"`
	Meta        *FileMeta `json:"meta,omitempty"`
}

FileInfo represents file or folder information.

type FileMeta

type FileMeta struct {
	Title       string   `json:"title,omitempty"`
	Description string   `json:"description,omitempty"`
	Tags        []string `json:"tags,omitempty"`
	Approved    *bool    `json:"approved,omitempty"`
}

FileMeta represents file metadata.

type FolderContents

type FolderContents struct {
	Contents     []FileInfo `json:"contents"`
	Continuation string     `json:"continuation,omitempty"`
}

FolderContents represents folder contents response.

type FolderOptions

type FolderOptions struct {
	ScanSpins    *bool `json:"scanSpins,omitempty"`
	AllowListing *bool `json:"allowListing,omitempty"`
}

FolderOptions represents folder options/settings.

type HTTPFetchingAuth

type HTTPFetchingAuth struct {
	Enabled  bool   `json:"enabled"`
	Username string `json:"username,omitempty"`
	Password string `json:"password,omitempty"`
}

HTTPFetchingAuth represents HTTP fetching authentication settings.

type HTTPFetchingConfig

type HTTPFetchingConfig struct {
	Auth *HTTPFetchingAuth `json:"auth,omitempty"`
	URL  string            `json:"url,omitempty"`
}

HTTPFetchingConfig represents HTTP fetching configuration details.

type HTTPStats

type HTTPStats struct {
	Date     string `json:"date"`
	Transfer int64  `json:"transfer"`
	Requests *int64 `json:"requests,omitempty"`
}

HTTPStats represents HTTP transfer statistics entry.

type JWTParams

type JWTParams struct {
	Filename     string            `json:"filename"`
	ExpiresIn    *int              `json:"expiresIn,omitempty"`
	SecureParams map[string]string `json:"secureParams,omitempty"`
}

JWTParams represents JWT generation parameters.

type JWTResponse

type JWTResponse struct {
	URL   string `json:"url"`
	Token string `json:"token"`
}

JWTResponse represents JWT generation response.

type MinifyOptions

type MinifyOptions struct {
	Enabled *bool `json:"enabled,omitempty"`
}

MinifyOptions represents minification settings.

type PlanPrice

type PlanPrice struct {
	Month   *float64 `json:"month,omitempty"`
	Year    *float64 `json:"year,omitempty"`
	Quarter *float64 `json:"quarter,omitempty"`
}

PlanPrice represents plan price information.

type PointOfInterest

type PointOfInterest struct {
	Name  string  `json:"name"`
	X     float64 `json:"x"`
	Y     float64 `json:"y"`
	Frame *int    `json:"frame,omitempty"`
}

PointOfInterest represents a point of interest on a spin.

type ProductMeta

type ProductMeta struct {
	ID       string `json:"id,omitempty"`
	Name     string `json:"name,omitempty"`
	Brand    string `json:"brand,omitempty"`
	Category string `json:"category,omitempty"`
	SKU      string `json:"sku,omitempty"`
}

ProductMeta represents product-specific metadata.

type RateLimitInfo

type RateLimitInfo struct {
	Limit     int    `json:"limit"`
	Remaining int    `json:"remaining"`
	Reset     string `json:"reset,omitempty"`
	Count     int    `json:"count"`
}

RateLimitInfo represents rate limit information for a specific endpoint type.

type RenameParams

type RenameParams struct {
	From string `json:"from"`
	To   string `json:"to"`
}

RenameParams represents rename/move operation parameters.

type SearchFilters

type SearchFilters struct {
	Dirname     string      `json:"dirname,omitempty"`
	Filename    string      `json:"filename,omitempty"`
	Basename    string      `json:"basename,omitempty"`
	Extension   interface{} `json:"extension,omitempty"`   // string or []string
	ContentType interface{} `json:"contentType,omitempty"` // string or []string
	MinSize     *int64      `json:"minSize,omitempty"`
	MaxSize     *int64      `json:"maxSize,omitempty"`
	MinDate     string      `json:"minDate,omitempty"`
	MaxDate     string      `json:"maxDate,omitempty"`
}

SearchFilters represents search filters.

type SearchParams

type SearchParams struct {
	Query   string         `json:"query,omitempty"`
	From    *int           `json:"from,omitempty"`
	Size    *int           `json:"size,omitempty"`
	Sort    *SortOptions   `json:"sort,omitempty"`
	Filters *SearchFilters `json:"filters,omitempty"`
}

SearchParams represents parameters for file search.

type SearchResult

type SearchResult struct {
	Hits     []FileInfo `json:"hits"`
	Total    int64      `json:"total"`
	ScrollID string     `json:"scrollId,omitempty"`
}

SearchResult represents search results.

type SortOptions

type SortOptions struct {
	Field string `json:"field"`
	Order string `json:"order"` // "asc" or "desc"
}

SortOptions represents sort options for search.

type SpinConvertOptions

type SpinConvertOptions struct {
	Width  *int   `json:"width,omitempty"`
	Height *int   `json:"height,omitempty"`
	Loops  *int   `json:"loops,omitempty"`
	Format string `json:"format,omitempty"`
}

SpinConvertOptions represents spin conversion options.

type SpinConvertParams

type SpinConvertParams struct {
	Filename string              `json:"filename"`
	Options  *SpinConvertOptions `json:"options,omitempty"`
}

SpinConvertParams represents spin to video conversion parameters.

type SpinViewStats

type SpinViewStats struct {
	Date        string `json:"date"`
	Views       int64  `json:"views"`
	Spins       *int64 `json:"spins,omitempty"`
	Zooms       *int64 `json:"zooms,omitempty"`
	Fullscreens *int64 `json:"fullscreens,omitempty"`
	UserAgent   string `json:"userAgent,omitempty"`
	Country     string `json:"country,omitempty"`
}

SpinViewStats represents spin view statistics entry.

type StatsParams

type StatsParams struct {
	From string `json:"from"`
	To   string `json:"to"`
}

StatsParams represents date range parameters for statistics.

type StorageInfo

type StorageInfo struct {
	Allowance int64  `json:"allowance"`
	Used      int64  `json:"used"`
	Files     int64  `json:"files"`
	Burstable *int64 `json:"burstable,omitempty"`
}

StorageInfo represents storage usage information.

type StorageStats

type StorageStats struct {
	Date    string `json:"date"`
	Storage int64  `json:"storage"`
	Files   *int64 `json:"files,omitempty"`
}

StorageStats represents storage statistics entry.

type TokenResponse

type TokenResponse struct {
	Token     string   `json:"token"`
	ExpiresIn int      `json:"expiresIn"`
	Scope     []string `json:"scope"`
}

TokenResponse represents the authentication token response.

type UploadOptions

type UploadOptions struct {
	Filename    string `json:"filename,omitempty"`
	ContentType string `json:"contentType,omitempty"`
}

UploadOptions represents upload options.

type UserInfo

type UserInfo struct {
	UserID      string `json:"userId"`
	Email       string `json:"email"`
	FirstName   string `json:"firstName,omitempty"`
	LastName    string `json:"lastName,omitempty"`
	DateCreated string `json:"dateCreated,omitempty"`
	S3Key       string `json:"s3Key,omitempty"`
	S3Secret    string `json:"s3Secret,omitempty"`
}

UserInfo represents user information.

type Video2SpinOptions

type Video2SpinOptions struct {
	Frames   *int     `json:"frames,omitempty"`
	Start    *float64 `json:"start,omitempty"`
	Duration *float64 `json:"duration,omitempty"`
}

Video2SpinOptions represents video to spin conversion options.

type Video2SpinParams

type Video2SpinParams struct {
	Filename       string             `json:"filename"`
	TargetFilename string             `json:"targetFilename,omitempty"`
	Options        *Video2SpinOptions `json:"options,omitempty"`
}

Video2SpinParams represents video to spin conversion parameters.

Directories

Path Synopsis
cmd
test command
Test program for the Sirv REST API Go SDK
Test program for the Sirv REST API Go SDK
Example usage of the Sirv REST API Go SDK
Example usage of the Sirv REST API Go SDK

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL