README

Build Status Coverage Status

go-sdk

A Go Integration for Transloadit's file uploading and encoding service

Intro

Transloadit is a service that helps you handle file uploads, resize, crop and watermark your images, make GIFs, transcode your videos, extract thumbnails, generate audio waveforms, and so much more. In short, Transloadit is the Swiss Army Knife for your files.

This is a Go SDK to make it easy to talk to the Transloadit REST API.

Install

go get gopkg.in/transloadit/go-sdk.v1

The Go SDK requires Go 1.7 or higher.

Usage

package main

import (
	"context"
	"fmt"

	"gopkg.in/transloadit/go-sdk.v1"
)

func main() {
	// Create client
	options := transloadit.DefaultConfig
	options.AuthKey = "YOUR_TRANSLOADIT_KEY"
	options.AuthSecret = "YOUR_TRANSLOADIT_SECRET"
	client := transloadit.NewClient(options)

	// Initialize new assembly
	assembly := transloadit.NewAssembly()

	// Add a file to upload
	assembly.AddFile("image", "/PATH/TO/FILE.jpg")

	// Add Instructions, e.g. resize image to 75x75px
	assembly.AddStep("resize", map[string]interface{}{
		"robot":           "/image/resize",
		"width":           75,
		"height":          75,
		"resize_strategy": "pad",
		"background":      "#000000",
	})

	// Start the upload
	info, err := client.StartAssembly(context.Background(), assembly)
	if err != nil {
		panic(err)
	}

	// All files have now been uploaded and the assembly has started but no
	// results are available yet since the conversion has not finished.
	// WaitForAssembly provides functionality for polling until the assembly
	// has ended.
	info, err = client.WaitForAssembly(context.Background(), info)
	if err != nil {
		panic(err)
	}

	fmt.Printf("You can view the result at: %s\n", info.Results["resize"][0].SSLURL)
}

Example

For fully working examples on how to use templates, non-blocking processing and more, take a look at examples/.

Documentation

See Godoc for full API documentation.

License

MIT Licensed

Expand ▾ Collapse ▴

Documentation

Overview

    Package transloadit provides a client to interact with the Transloadt API.

    Index

    Constants

    This section is empty.

    Variables

    View Source
    var DefaultConfig = Config{
    	Endpoint: "https://api2.transloadit.com",
    }

      DefaultConfig is the recommended base configuration.

      View Source
      var Version = "v1.2.0"

        Version specifies the version of the Go SDK.

        Functions

        This section is empty.

        Types

        type Assembly

        type Assembly struct {
        	// NotifiyURL specifies a URL to which a request will be sent once the
        	// assembly finishes.
        	// See https://transloadit.com/docs#notifications.
        	NotifyURL string
        	// TemplateID specifies a optional template from which the encoding
        	// instructions will be fetched.
        	// See https://transloadit.com/docs/#15-templates
        	TemplateID string
        	// contains filtered or unexported fields
        }

          Assembly contains instructions used for starting assemblies.

          func NewAssembly

          func NewAssembly() Assembly

            NewAssembly will create a new Assembly struct which can be used to start an assembly using Client.StartAssembly.

            func (*Assembly) AddFile

            func (assembly *Assembly) AddFile(fieldname, filepath string) error

              AddFile will open the provided file path and add it to the list which will be uploaded once Client.StartAssembly is invoked. The corresponding field name can be used to reference the file in the assembly instructions.

              func (*Assembly) AddReader

              func (assembly *Assembly) AddReader(fieldname, filename string, reader io.ReadCloser)

                AddReader will add the provided io.Reader to the list which will be uploaded once Client.StartAssembly is invoked. The corresponding field name can be used to reference the file in the assembly instructions.

                func (*Assembly) AddStep

                func (assembly *Assembly) AddStep(name string, details map[string]interface{})

                  AddStep will add the provided step to the assembly instructions. Details about possible values can be found at https://transloadit.com/docs/#14-assembly-instructions

                  type AssemblyInfo

                  type AssemblyInfo struct {
                  	Ok      string `json:"ok"`
                  	Error   string `json:"error"`
                  	Message string `json:"message"`
                  
                  	AssemblyID             string                 `json:"assembly_id"`
                  	ParentID               string                 `json:"parent_id"`
                  	AssemblyURL            string                 `json:"assembly_url"`
                  	AssemblySSLURL         string                 `json:"assembly_ssl_url"`
                  	BytesReceived          int                    `json:"bytes_received"`
                  	BytesExpected          int                    `json:"bytes_expected"`
                  	StartDate              string                 `json:"start_date"`
                  	IsInfinite             bool                   `json:"is_infinite"`
                  	HasDupeJobs            bool                   `json:"has_dupe_jobs"`
                  	UploadDuration         float32                `json:"upload_duration"`
                  	NotifyURL              string                 `json:"notify_url"`
                  	NotifyStart            string                 `json:"notify_start"`
                  	NotifyStatus           string                 `json:"notify_status"`
                  	NotifyDuation          float32                `json:"notify_duration"`
                  	LastJobCompleted       string                 `json:"last_job_completed"`
                  	ExecutionDuration      float32                `json:"execution_duration"`
                  	ExecutionStart         string                 `json:"execution_start"`
                  	Created                string                 `json:"created"`
                  	Files                  string                 `json:"files"`
                  	Fields                 map[string]interface{} `json:"fields"`
                  	BytesUsage             int                    `json:"bytes_usage"`
                  	FilesToStoreOnS3       int                    `json:"files_to_store_on_s3"`
                  	QueuedFilesToStoreOnS3 int                    `json:"queued_files_to_store_on_s3"`
                  	ExecutingJobs          []string               `json:"executing_jobs"`
                  	StartedJobs            []string               `json:"started_jobs"`
                  	ParentAssemblyStatus   *AssemblyInfo          `json:"parent_assembly_status"`
                  	Uploads                []*FileInfo            `json:"uploads"`
                  	Results                map[string][]*FileInfo `json:"results"`
                  	Params                 string                 `json:"params"`
                  
                  	// Since 7 March 2018, the user agent, IP and referer are no longer
                  	// stored by Transloadit (see https://transloadit.com/blog/2018/03/gdpr/)
                  	// Therefore, these properties will always hold empty strings.
                  	ClientAgent   string
                  	ClientIp      string
                  	ClientReferer string
                  }

                    AssemblyInfo contains details about an assemblies current status. Details about each value can be found at https://transloadit.com/docs/api-docs/#assembly-status-response

                    type AssemblyList

                    type AssemblyList struct {
                    	Assemblies []*AssemblyListItem `json:"items"`
                    	Count      int                 `json:"count"`
                    }

                      AssemblyList contains a list of assemblies.

                      type AssemblyListItem

                      type AssemblyListItem struct {
                      	Ok    string `json:"ok"`
                      	Error string `json:"error"`
                      
                      	AssemblyID        string     `json:"id"`
                      	AccountID         string     `json:"account_id"`
                      	TemplateID        string     `json:"template_id"`
                      	Instance          string     `json:"instance"`
                      	NotifyURL         string     `json:"notify_url"`
                      	RedirectURL       string     `json:"redirect_url"`
                      	ExecutionDuration float32    `json:"execution_duration"`
                      	ExecutionStart    *time.Time `json:"execution_start"`
                      	Created           time.Time  `json:"created"`
                      	Files             string     `json:"files"`
                      }

                        AssemblyListItem contains reduced details about an assembly.

                        type AssemblyReplay

                        type AssemblyReplay struct {
                        	// NotifiyURL specifies a URL to which a request will be sent once the
                        	// assembly finishes. This overwrites the notify url from the original
                        	// assembly instructions.
                        	// See https://transloadit.com/docs#notifications.
                        	NotifyURL string
                        	// ReparseTemplate specifies whether the template should be fetched again
                        	// before the assembly is replayed. This can be used if the template has
                        	// changed since the original assembly was created.
                        	ReparseTemplate bool
                        	// contains filtered or unexported fields
                        }

                          AssemblyReplay contains instructions used for replaying assemblies.

                          func NewAssemblyReplay

                          func NewAssemblyReplay(assemblyURL string) AssemblyReplay

                            NewAssemblyReplay will create a new AssemblyReplay struct which can be used to replay an assemblie's execution using Client.StartAssemblyReplay. The assembly URL must be absolute, for example: https://api2-amberly.transloadit.com/assemblies/15a6b3701d3811e78d7bfba4db1b053e

                            func (*AssemblyReplay) AddStep

                            func (assembly *AssemblyReplay) AddStep(name string, details map[string]interface{})

                              AddStep will add the provided step to the new assembly instructions. When the assembly is replayed, those new steps will be used instead of the original ones. Details about possible values can be found at https://transloadit.com/docs/#14-assembly-instructions.

                              type Client

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

                                Client provides an interface to the Transloadit REST API bound to a specific account.

                                func NewClient

                                func NewClient(config Config) Client

                                  NewClient creates a new client using the provided configuration struct. It will panic if no Config.AuthKey or Config.AuthSecret are empty.

                                  func (*Client) CancelAssembly

                                  func (client *Client) CancelAssembly(ctx context.Context, assemblyURL string) (*AssemblyInfo, error)

                                    CancelAssembly cancels an assembly which will result in all corresponding uploads and encoding jobs to be aborted. Finally, the updated assembly information after the cancellation will be returned. The assembly URL must be absolute, for example: https://api2-amberly.transloadit.com/assemblies/15a6b3701d3811e78d7bfba4db1b053e

                                    func (*Client) CreateTemplate

                                    func (client *Client) CreateTemplate(ctx context.Context, template Template) (string, error)

                                      CreateTemplate will save the provided template struct as a new template and return the ID of the new template.

                                      func (*Client) DeleteTemplate

                                      func (client *Client) DeleteTemplate(ctx context.Context, templateID string) error

                                        DeleteTemplate will delete the template associated with the provided template ID.

                                        func (*Client) GetAssembly

                                        func (client *Client) GetAssembly(ctx context.Context, assemblyURL string) (*AssemblyInfo, error)

                                          GetAssembly fetches the full assembly status from the provided URL. The assembly URL must be absolute, for example: https://api2-amberly.transloadit.com/assemblies/15a6b3701d3811e78d7bfba4db1b053e

                                          func (*Client) GetTemplate

                                          func (client *Client) GetTemplate(ctx context.Context, templateID string) (template Template, err error)

                                            GetTemplate will retrieve details about the template associated with the provided template ID.

                                            func (*Client) ListAssemblies

                                            func (client *Client) ListAssemblies(ctx context.Context, options *ListOptions) (AssemblyList, error)

                                              ListAssemblies will fetch all assemblies matching the provided criteria.

                                              func (*Client) ListNotifications

                                              func (client *Client) ListNotifications(ctx context.Context, options *ListOptions) (list NotificationList, err error)

                                                ListNotifications will return a list containing all notifications matching the criteria defined using the ListOptions structure.

                                                func (*Client) ListTemplates

                                                func (client *Client) ListTemplates(ctx context.Context, options *ListOptions) (list TemplateList, err error)

                                                  ListTemplates will retrieve all templates matching the criteria.

                                                  func (*Client) ReplayNotification

                                                  func (client *Client) ReplayNotification(ctx context.Context, assemblyID string, notifyURL string) error

                                                    ReplayNotification instructs the endpoint to replay the notification corresponding to the provided assembly ID. If notifyURL is not empty it will override the notify URL used in the assembly instructions.

                                                    func (*Client) StartAssembly

                                                    func (client *Client) StartAssembly(ctx context.Context, assembly Assembly) (*AssemblyInfo, error)

                                                      StartAssembly will upload all provided files and instruct the endpoint to start executing it. The function will return after all uploads complete and the remote server received the instructions (or the provided context times out). It won't wait until the execution has finished and results are available, which can be achieved using WaitForAssembly.

                                                      When an error is returned you should also check AssemblyInfo.Error for more information about the error sent by the Transloadit API:

                                                      info, err := assembly.Upload()
                                                      if err != nil {
                                                      	if info != nil && info.Error != "" {
                                                      		// See info.Error
                                                      	}
                                                      	panic(err)
                                                      }
                                                      

                                                      func (*Client) StartAssemblyReplay

                                                      func (client *Client) StartAssemblyReplay(ctx context.Context, assembly AssemblyReplay) (*AssemblyInfo, error)

                                                        StartAssemblyReplay will instruct the endpoint to replay the entire assembly execution.

                                                        func (*Client) UpdateTemplate

                                                        func (client *Client) UpdateTemplate(ctx context.Context, templateID string, newTemplate Template) error

                                                          UpdateTemplate will update the template associated with the provided template ID to match the new name and new content. Please be aware that you are not able to change a template's ID.

                                                          func (*Client) WaitForAssembly

                                                          func (client *Client) WaitForAssembly(ctx context.Context, assembly *AssemblyInfo) (*AssemblyInfo, error)

                                                            WaitForAssembly fetches continuously the assembly status until it has finished uploading and executing or until an assembly error occurs. If you want to end this loop prematurely, you can cancel the supplied context.

                                                            type Config

                                                            type Config struct {
                                                            	AuthKey    string
                                                            	AuthSecret string
                                                            	Endpoint   string
                                                            }

                                                              Config defines the configuration options for a client.

                                                              type FileInfo

                                                              type FileInfo struct {
                                                              	ID               string                 `json:"id"`
                                                              	Name             string                 `json:"name"`
                                                              	Basename         string                 `json:"basename"`
                                                              	Ext              string                 `json:"ext"`
                                                              	Size             int                    `json:"size"`
                                                              	Mime             string                 `json:"mime"`
                                                              	Type             string                 `json:"type"`
                                                              	Field            string                 `json:"field"`
                                                              	Md5Hash          string                 `json:"md5hash"`
                                                              	OriginalMd5Hash  string                 `json:"original_md5hash"`
                                                              	OriginalID       string                 `json:"original_id"`
                                                              	OriginalBasename string                 `json:"original_basename"`
                                                              	URL              string                 `json:"url"`
                                                              	SSLURL           string                 `json:"ssl_url"`
                                                              	Meta             map[string]interface{} `json:"meta"`
                                                              }

                                                                FileInfo contains details about a file which was either uploaded or is the result of an executed assembly.

                                                                type ListOptions

                                                                type ListOptions struct {
                                                                	Page       int        `json:"page,omitempty"`
                                                                	PageSize   int        `json:"pagesize,omitempty"`
                                                                	Sort       string     `json:"sort,omitempty"`
                                                                	Order      string     `json:"order,omitempty"`
                                                                	Fields     []string   `json:"fields,omitempty"`
                                                                	Type       string     `json:"type,omitempty"`
                                                                	Keywords   []string   `json:"keyword,omitempty"`
                                                                	AssemblyID string     `json:"assembly_id,omitempty"`
                                                                	FromDate   *time.Time `json:"fromdate,omitempty"`
                                                                	ToDate     *time.Time `json:"todate,omitempty"`
                                                                }

                                                                  ListOptions defines criteria used when a list is being retrieved. Details about each property can be found at https://transloadit.com/docs/api-docs#retrieve-assembly-list.

                                                                  type Notification

                                                                  type Notification struct {
                                                                  	ID           string    `json:"id"`
                                                                  	AssemblyID   string    `json:"assembly_id"`
                                                                  	AccountID    string    `json:"account_id"`
                                                                  	URL          string    `json:"url"`
                                                                  	ResponseCode int       `json:"response_code"`
                                                                  	ResponseData string    `json:"response_data"`
                                                                  	Duration     float32   `json:"duration"`
                                                                  	Created      time.Time `json:"created"`
                                                                  	Error        string    `json:"error"`
                                                                  }

                                                                    Notification contains details about a notification.

                                                                    type NotificationList

                                                                    type NotificationList struct {
                                                                    	Notifications []Notification `json:"items"`
                                                                    	Count         int            `json:"count"`
                                                                    }

                                                                      NotificationList contains a list of notifications.

                                                                      type RequestError

                                                                      type RequestError struct {
                                                                      	Code    string `json:"error"`
                                                                      	Message string `json:"message"`
                                                                      }

                                                                        RequestError represents an error returned by the Transloadit API alongside additional service-specific information.

                                                                        func (RequestError) Error

                                                                        func (err RequestError) Error() string

                                                                          Error return a formatted message describing the error.

                                                                          type Template

                                                                          type Template struct {
                                                                          	ID                   string
                                                                          	Name                 string
                                                                          	Content              TemplateContent
                                                                          	RequireSignatureAuth bool
                                                                          }

                                                                            Template contains details about a single template.

                                                                            func NewTemplate

                                                                            func NewTemplate() Template

                                                                              NewTemplate returns a new Template struct with initialized values. This template will not be saved to Transloadit. To do so, please use the Client.CreateTemplate function.

                                                                              func (*Template) AddStep

                                                                              func (template *Template) AddStep(name string, step map[string]interface{})

                                                                                AddStep will add the provided step to the Template.Content.Steps map.

                                                                                func (Template) MarshalJSON

                                                                                func (template Template) MarshalJSON() ([]byte, error)

                                                                                func (*Template) UnmarshalJSON

                                                                                func (template *Template) UnmarshalJSON(b []byte) error

                                                                                type TemplateContent

                                                                                type TemplateContent struct {
                                                                                	Steps map[string]interface{} `json:"steps"`
                                                                                }

                                                                                  TemplateContent contains details about the content of a single template.

                                                                                  type TemplateList

                                                                                  type TemplateList struct {
                                                                                  	Templates []Template `json:"items"`
                                                                                  	Count     int        `json:"count"`
                                                                                  }

                                                                                    TemplateList contains a list of templates.

                                                                                    Directories

                                                                                    Path Synopsis