Go SDK

This page provides an in-depth introduction to the Go SDK.

Tip
If you're ready to get coding, jump straight to our quick start.

Overview

Cloudinary's Go SDK provides simple, yet comprehensive media upload and management capabilities that you can implement using code that integrates seamlessly with your existing Go application. The Go SDK also enables you to generate asset URLs, with or without transformations applied, for delivering Cloudinary assets within your application.

This guide relates to versions 2.x of Cloudinary's Go SDK. Cloudinary no longer supports versions 1.x. For breaking changes, see Update.

Tip
In this guide you'll learn how to get started with the Go SDK, but if you are not familiar with Cloudinary, we advise starting with the Developer get started guide for a high-level overview of integrating Cloudinary into your code, and an introduction to the main concepts.

You may also find our Glossary helpful to understand Cloudinary-specific terminology.

Related topics
This guide relates to the latest released version of the Cloudinary Go library.

Architecture

The @cloudinary-go library contains all the functionality required to upload, manage, and create delivery URLs for your Cloudinary assets based on the configuration and transformation actions that you specify.

Code samples

1. Import packages

Copy to clipboard
// Import the required packages for upload and admin.

import (
    "context"
    "github.com/cloudinary/cloudinary-go/v2"
    "github.com/cloudinary/cloudinary-go/v2/api/admin"
    "github.com/cloudinary/cloudinary-go/v2/api/uploader"
    "log"
)

2. Add configuration

Copy to clipboard
// Add your Cloudinary credentials.

cld, _ := cloudinary.NewFromParams("<your-cloud-name>", "<your-api-key>", "<your-api-secret>")

Learn more: Account configuration

3. Upload image

Copy to clipboard
// Upload the my_picture.jpg image and set the PublicID to "my_image". 

resp, err := cld.Upload.Upload(ctx, "my_picture.jpg", uploader.UploadParams{PublicID: "my_image"});

Learn more: Image and video upload

4. Get image details

Copy to clipboard
// Get details about the image with PublicID "my_image" and log the secure URL.

resp, err := cld.Admin.Asset(ctx, admin.AssetParams{PublicID: "my_image"});
if err != nil {...}
log.Println(resp.SecureURL)

Learn more: Asset management and administration

5. Transform and deliver an image

Copy to clipboard
// Instantiate an object for the asset with public ID "my_image"
my_image, err := cld.Image("my_image")
if err != nil {
    fmt.Println("error")
}

// Add the transformation
my_image.Transformation = "c_fill,h_250,w_250"

// Generate and print the delivery URL
url, err := my_image.String()
if err != nil {
    fmt.Println("error")
}

Installation

Create a go.mod file in the directory where your Go program will be saved:

Copy to clipboard
go mod init my_folder

Install the Cloudinary Go SDK using the go get command:

Copy to clipboard
go get github.com/cloudinary/cloudinary-go/v2

Update

To update the Cloudinary Go SDK to the latest version, use the go get command with the -u option:

Copy to clipboard
go get -u github.com/cloudinary/cloudinary-go/v2

Migrating to versions 2.x

When migrating from versions 1.x to 2.x, note the following changes:

  • Include /v2 in the path when importing Cloudinary libraries, for example: github.com/cloudinary/cloudinary-go/v2/api/admin.
  • Parameters that were of type bool are now of type *bool and must be passed as pointers to boolean variables. You can use the api.Bool(true) and api.Bool(false) helper methods to pass the desired values.
  • Some parameter names have changed. Specifically:
    • Instances of Ids in parameter names are now IDs. For example, the PublicIds parameter of the DownloadZipURL method is now PublicIDs.
    • Instances of Url in parameter names are now URL. For example, PrivateDownloadUrl is now PrivateDownloadURL.
    • Instances of Api in parameter names are now API.

Configuration

For requests to our secure APIs (e.g., image uploads, asset administration) you must have the APIKey and APISecret parameters set. You can find your account-specific configuration credentials in the Dashboard page of the account console.

Setting your CloudName, APIKey and APISecret parameters can be done by initializing the Cloudinary object, or by using the CLOUDINARY_URL environment variable / system property.

Setting parameters globally

The entry point of the library is the Cloudinary struct.

Copy to clipboard
cld, _ := cloudinary.New()

Here's an example of setting the configuration parameters programatically:

Copy to clipboard
cld, _ := cloudinary.NewFromParams("n07t21i7", "123456789012345", "abcdeghijklmnopqrstuvwxyz12")

Setting the CLOUDINARY_URL environment variable

You can configure the required cloud_name, api_key, and api_secret by defining the CLOUDINARY_URL environment variable. The CLOUDINARY_URL value is available in the Dashboard page of the account console. When using Cloudinary through a PaaS add-on (e.g., Heroku or AppFog), this environment variable is automatically defined in your deployment environment. For example:

Copy to clipboard
CLOUDINARY_URL=cloudinary://my_key:my_secret@my_cloud_name

Set additional parameters, for example upload_prefix and cname, to the environment variable:

Copy to clipboard
CLOUDINARY_URL=cloudinary://my_key:my_secret@my_cloud_name?cname=mydomain.com&upload_prefix=myprefix.com

Complete SDK Example

Copy to clipboard
package main

import (
    "context"
    "github.com/cloudinary/cloudinary-go/v2"
    "github.com/cloudinary/cloudinary-go/v2/api/admin"
    "github.com/cloudinary/cloudinary-go/v2/api/admin/search"
    "github.com/cloudinary/cloudinary-go/v2/api/uploader"
    "log"
)

func main() {
    // Start by creating a new instance of Cloudinary using CLOUDINARY_URL environment variable.
    // Alternatively you can use cloudinary.NewFromParams() or cloudinary.NewFromURL().
    var cld, err = cloudinary.New()
    if err != nil {
        log.Fatalf("Failed to intialize Cloudinary, %v", err)
    }

    var ctx = context.Background()

    // Upload an image to your Cloudinary account from a specified URL.
    //
    // Alternatively you can provide a path to a local file on your filesystem,
    // base64 encoded string, io.Reader and more.
    //
    // For additional information see:
    // https://cloudinary.com/documentation/upload_images
    //
    // Upload can be greatly customized by specifying uploader.UploadParams,
    // in this case we set the Public ID of the uploaded asset to "logo".
    uploadResult, err := cld.Upload.Upload(
        ctx,
        "https://cloudinary-res.cloudinary.com/image/upload/cloudinary_logo.png",
        uploader.UploadParams{PublicID: "logo"})
    if err != nil {
        log.Fatalf("Failed to upload file, %v\n", err)
    }

    log.Println(uploadResult.SecureURL)
    // Prints something like:
    // https://res.cloudinary.com/<your cloud name>/image/upload/v1615875158/logo.png

    // uploadResult contains useful information about the asset, like Width, Height, Format, etc.
    // See uploader.UploadResult struct for more details.

    // Now we can use Admin API to see the details about the asset.
    // The request can be customised by providing AssetParams.
    asset, err := cld.Admin.Asset(ctx, admin.AssetParams{PublicID: "logo"})
    if err != nil {
        log.Fatalf("Failed to get asset details, %v\n", err)
    }

    // Print some basic information about the asset.
    log.Printf("Public ID: %v, URL: %v\n", asset.PublicID, asset.SecureURL)

    // Cloudinary also provides a very flexible Search API for filtering and retrieving
    // information on all the assets in your account with the help of query expressions
    // in a Lucene-like query language.
    searchQuery := search.Query{
        Expression: "resource_type:image AND uploaded_at>1d AND bytes<1m",
        SortBy:     []search.SortByField{{"created_at": search.Descending}},
        MaxResults: 30,
    }

    searchResult, err := cld.Admin.Search(ctx, searchQuery)

    if err != nil {
        log.Fatalf("Failed to search for assets, %v\n", err)
    }

    log.Printf("Assets found: %v\n", searchResult.TotalCount)

    for _, asset := range searchResult.Assets {
        log.Printf("Public ID: %v, URL: %v\n", asset.PublicID, asset.SecureURL)
    }
}

Related topics

✔️ Feedback sent!

Rate this page: