> ## Documentation Index
> Fetch the complete documentation index at: https://cloudinary.com/documentation/llms.txt
> Use this file to discover all available pages before exploring further.

# Go SDK


[sample-projects-link]:go_sample_projects
[changelog-link]: https://github.com/cloudinary/cloudinary-go/blob/main/CHANGELOG.md

The Cloudinary Go SDK provides simple, yet comprehensive image and video upload, transformation, optimization, and delivery capabilities through the [Cloudinary APIs](cloudinary_references#url_and_rest_apis), that you can implement using code that integrates seamlessly with your existing Go application.
> **INFO**: :title=SDK security upgrade, June 2025

We recently released an enhanced security version of this SDK that improves the validation and handling of input parameters. We recommend upgrading to the [latest version][changelog-link] of the SDK to benefit from these security improvements.

## How would you like to learn?

{table:class=no-borders overview}Resource | Description 
--|--
[Go quick start](go_quick_start) | Get up and running in five minutes with a walk through of installation, configuration, upload, management and transformations.
[Video tutorials](go_video_tutorials) | Watch tutorials relevant to your use cases, from getting started with the Go SDK, to uploading, transforming and analyzing your images and videos. 
[Sample projects](go_sample_projects) | Explore sample projects to see how to implement Cloudinary functionality such as upload and delivery with transformations.
[Cloudinary Go SDK GitHub repo](https://github.com/cloudinary/cloudinary-go) | Explore the source code and see the [CHANGELOG][changelog-link] for details on all new features and fixes from previous versions. 

Other helpful resources...

This guide focuses on how to set up and implement popular Cloudinary capabilities using the Go SDK, but it doesn't cover every feature or option. Check out these other resources to learn about additional concepts and functionality in general. 

{table:class=no-borders overview}Resource | Description 
--|--
[Developer kickstart](dev_kickstart) |A hands-on, step-by-step introduction to Cloudinary features.
[Glossary](cloudinary_glossary) | A helpful resource to understand Cloudinary-specific terminology.
[Guides](programmable_media_guides) | In depth guides to help you understand the many, varied capabilities provided by the product. 
[References](cloudinary_references) | Comprehensive references for all APIs, including Go code examples.

> **INFO**: :title=SDK security upgrade, June 2025

We recently released an enhanced security version of this SDK that improves the validation and handling of input parameters. We recommend upgrading to the [latest version][changelog-link] of the SDK to benefit from these security improvements.

## Install

Cloudinary's Go integration library is available as an open-source package. 

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

```terminal
go mod init my_folder
```

To install the library, run:

```terminal
go get github.com/cloudinary/cloudinary-go/v2
```

> **NOTE**: This guide relates to versions 2.x of Cloudinary's Go SDK. Cloudinary no longer supports versions 1.x. For breaking changes, see [Update](#update).

### Update 

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

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

## Configure

Import the required packages for upload and admin:

```go
import (
    "context"
	"log"

    "github.com/cloudinary/cloudinary-go/v2"
	"github.com/cloudinary/cloudinary-go/v2/api"
	"github.com/cloudinary/cloudinary-go/v2/api/admin"
	"github.com/cloudinary/cloudinary-go/v2/api/uploader"
)
```

### Set required configuration parameters

For requests to our secure APIs (e.g., image uploads, asset management) you must have the `APIKey` and `APISecret` parameters set. You can find your product environment configuration credentials in the [API Keys](https://console.cloudinary.com/app/settings/api-keys) page of the Cloudinary Console Settings.

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

To define the `CLOUDINARY_URL` environment variable:

1. Copy the **API environment variable** format from the [API Keys](https://console.cloudinary.com/app/settings/api-keys) page of the Cloudinary Console Settings. 
2. Replace `<api_key>` and `<api_secret>` with your actual values. Your cloud name is already correctly included in the format. 
 
For example:

```
CLOUDINARY_URL=cloudinary://<api_key>:<api_secret>@<cloud_name>
```

> **NOTE**: When using Cloudinary through a PaaS add-on, such as Heroku, this environment variable is automatically defined in your deployment environment.

The entry point of the library is the Cloudinary struct. Here's an example of setting up your configuration using your **API environment variable**:

```go
cld, err := cloudinary.NewFromURL("cloudinary://<api_key>:<api_secret>@<cloud_name>")
```

Alternatively, you can pass your `CloudName`, `APIKey` and `APISecret` as parameters:

```go
cld, _ := cloudinary.NewFromParams("<cloud_name>", "<api_key>", "<api_secret>")
```

Or initialize a new Cloudinary instance (if you've already set the environment variable):

```go
cld, _ := cloudinary.New()
```

> **INFO**:
>
> * When writing your own applications, follow your organization's policy on storing secrets and don't expose your API secret. * If you use a method that involves writing your environment variable to a file (e.g. `dotenv`), exclude the file from your version control system, so as not to expose it publicly.
> **TIP**: To generate transformation URLs, you only need to configure the cloud name. The API key and API secret aren't required for URL generation.
### Set additional configuration parameters

In addition to the required configuration parameters, you can define a number of optional [configuration parameters](cloudinary_sdks#configuration_parameters) if relevant.

You can append configuration parameters, for example `upload_prefix` and `secure_distribution`, to the environment variable:

```
CLOUDINARY_URL=cloudinary://<api_key>:<api_secret>@<cloud_name>?secure_distribution=mydomain.com&upload_prefix=https://api-eu.cloudinary.com
```

Or use the `NewFromURL` method:

```go
cld, err := cloudinary.NewFromURL("cloudinary://<api_key>:<api_secret>@<cloud_name>?secure_distribution=mydomain.com&upload_prefix=https://api-eu.cloudinary.com")
```

Or you can set them by accessing the Config struct fields (using PascalCase field names):

```go
cld, _ := cloudinary.NewFromParams("<cloud_name>", "<api_key>", "<api_secret>")
cld.Config.URL.SecureDistribution = "mydomain.com"
cld.Config.URL.UploadPrefix = "https://api-eu.cloudinary.com"
```

> **NOTE**: By default, URLs generated with this SDK include an appended SDK-usage query parameter. Cloudinary tracks aggregated data from this parameter to improve future SDK versions. We don't collect any individual data. If needed, you can disable the `urlAnalytics` configuration option. [Learn more](cloudinary_sdks#analytics_config).

### Configuration video tutorial

Watch this video tutorial to see how to install and configure the Go SDK:

  This video is brought to you by Cloudinary's video player - embed your own!Use the controls to set the playback speed, navigate to chapters of interest and select subtitles in your preferred language.

Tutorial contents...

This tutorial presents the following topics. Click a timestamp to jump to that part of the video.
### Introduction
{table:class=tutorial-bullets}|  | 
| --- | --- |
|{videotime:id=media :min=0 :sec=00 :player=cld} | The [Cloudinary Go SDK](go_integration) gives you a way to handle images and videos at scale, providing transformation, optimization and delivery capabilities that you can integrate seamlessly into your Go applications. 
|

### Install the Go SDK
{table:class=tutorial-bullets}|  | 
| --- | --- |
|{videotime:id=media :min=0 :sec=17 :player=cld} | To install the Cloudinary Go SDK, ensure you're in the directory where your Go module was initialized using `go mod init`. Use the `go get` command to add the Cloudinary Go [library](https://github.com/cloudinary/cloudinary-go) from GitHub to your project.
|

```go
go get github.com/cloudinary/cloudinary-go/v2
```

### Configure Cloudinary
{table:class=tutorial-bullets}|  | 
| --- | --- |
|{videotime:id=media :min=0 :sec=29 :player=cld} | To configure Cloudinary, begin by creating a Cloudinary instance. Import the Cloudinary library from GitHub and use the `cloudinary.New` function to create the instance. Store this instance in a variable, such as `cld`, and include error handling.
|

my_file.go

```go
import {
    "github.com/cloudinary/cloudinary-go/v2"
}

func main() {
    cld, err := cloudinary.New()
    if err != nil {
        log.Fatalf("failed to initialize Cloudinary client: %v", err)
    }
}
```
### Add credentials
{table:class=tutorial-bullets}|  | 
| --- | --- |
|{videotime:id=media :min=0 :sec=48 :player=cld} | To keep your credentials secure:Store them in a `.env` file.Install the library with `go get github.com/joho/godotenv`.Import the `godotenv` library in your code.Use `godotenv.Load()` to load the credentials into your Go file.Retrieve your Cloudinary credentials from the [API Keys](https://console.cloudinary.com/app/settings/api-keys) page in the Cloudinary Console. Copy the provided **API environment variable** format (containing the **Cloud Name**, **API Key**, and **API Secret**) and paste it into your `.env` file, replacing the placeholder values with your actual credentials. 
|

```go
go get github.com/joho/godotenv
```

my_file.go

```go
import {
    "github.com/cloudinary/cloudinary-go/v2"
    "github.com/joho/godotenv"
}

func main() {
    err := godotenv.Load()
    if err != nil {
        log.Fatalf("Error loading .env file: %v", err)
    }
    cld, err := cloudinary.New()
    if err != nil {
        log.Fatalf("failed to initialize Cloudinary client: %v", err)
    }
}
```

### Retrieve an image delivery URL from Cloudinary
{table:class=tutorial-bullets}|  | 
| --- | --- |
|{videotime:id=media :min=2 :sec=03 :player=cld} | With your Cloudinary instance configured, you can generate a delivery URL for an image in your product environment: Use the `cld.Image` function with the public ID of the desired image to create an image object. For this example, you can use the public ID of a sample image `cld-sample` provided with every new Cloudinary account. Store this object in a variable named `img` and handle any errors. Convert the image object to a string to generate the delivery URL. Include error handling and print the URL upon success.|

my_file.go

```go
import {
    "github.com/cloudinary/cloudinary-go/v2"
    "github.com/joho/godotenv"
}

func main() {
    err := godotenv.Load()
    if err != nil {
        log.Fatalf("Error loading .env file: %v", err)
    }
    cld, err := cloudinary.New()
    if err != nil {
        log.Fatalf("failed to initialize Cloudinary client: %v", err)
    }

    img, err :=cld.Image("cld-sample")
    if err !=nil {
        fmt.Println("error")
    }

    url, err := img.String()
    if err != nil {
        fmr.Pringln("error")
    } else {
        fmt.Println("Image URL: ", url)
    }
}
```

### Run the code
{table:class=tutorial-bullets}|  | 
| --- | --- |
|{videotime:id=media :min=2 :sec=51 :player=cld} | After writing the code, run it to see the delivery URL for the `cld-sample` image. This confirms that your Cloudinary instance was successfully created and used. You can also open the URL in a browser to view the image in your product environment.
|

## Use

Once you've installed and configured the Go SDK, you can use it for:
* **Uploading files to your product environment**: You can upload any files, not only images and videos, set your own naming conventions and overwrite policies, moderate and tag your assets on upload, and much more. [See&nbsp;example](#quick_example_file_upload)
* **Transforming and optimizing images and videos**: Keeping your original assets intact in your product environment, you can deliver different versions of your media - different sizes, formats, with effects and overlays, customized for your needs. [See&nbsp;example](#quick_example_transform_and_optimize)
* **Managing assets**: Using methods from the Admin and Upload APIs, you can organize your assets, for example, list, rename and delete them, add tags and metadata and use advanced search capabilities. [See&nbsp;example](#quick_example_get_details_of_a_single_asset)

Capitalization and data type guidelines...

When using the Go SDK, keep these guidelines in mind:  

* Parameter names: `PascalCase`. For example: **PublicID**
* Struct names: `PascalCase`. For example: **UploadParams**
* Methods: `PascalCase`. For example: **Upload**
* Pass parameter data as: `Struct`
* Boolean parameters are 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.

### Quick example: File upload

The following Go code uploads the `dog.mp4` video using the PublicID, `my_dog`. The video overwrites the existing `my_dog` video if it exists. When the video upload finishes, the specified notification URL receives details about the uploaded media asset.

```go
var ctx = context.Background()
resp, err := cld.Upload.Upload(ctx, "dog.mp4", uploader.UploadParams{
  ResourceType: "video", 
  PublicID: "my_dog",
  Overwrite: api.Bool(true), 
  NotificationURL: "https://mysite.example.com/notify_endpoint"})
```

> **Learn more about upload**:
>
> * Read the [Upload guide](upload_images) to learn more about customizing uploads, using upload presets and more.

> * See more examples of [image and video upload](go_image_and_video_upload) using the Cloudinary Go library.  

> * Explore the [Upload API reference](image_upload_api_reference) to see all available methods and options.

### Quick example: Transform and optimize

Take a look at the following transformation code and the image it delivers:

```go
// Instantiate an object for the image with PublicID "front_face"
img, err := cld.Image("front_face")
if err != nil {
	fmt.Println("error")
}

// Add the transformation by passing the transformation string directly
img.Transformation = "c_thumb,g_face,h_150,w_150/r_20/e_sepia/l_cloudinary_icon/e_brightness:90/o_60/c_scale,w_50/fl_layer_apply,g_south_east,x_5,y_5/a_10/q_auto/f_png"

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

In the Go SDK, transformations are applied by passing the transformation string directly to the `Transformation` parameter. The transformation string uses the same syntax as the [Transformation URL API](transformation_reference), with individual transformations separated by commas and transformation chains separated by forward slashes.

This relatively simple transformation string performs all of the following on the original front_face.jpg image before delivering it:

* **Crop** to a 150x150 thumbnail using face-detection gravity to automatically determine the location for the crop
* **Round the corners** with a 20 pixel radius
* Apply a **sepia effect**
* **Overlay the Cloudinary logo** on the southeast corner of the image (with a slight offset). Scale the logo overlay down to a 50 pixel width, with increased brightness and partial transparency (opacity = 60%).
* **Rotate** the resulting image (including the overlay) by 10 degrees
* **Optimize** the image to reduce the size of the image without impacting visual quality.
* **Convert** and deliver the image in PNG format (the originally uploaded image was a JPG)

And here's the URL that's generated:

![sample transformation](https://res.cloudinary.com/demo/image/upload/c_thumb,g_face,h_150,w_150/r_20/e_sepia/l_cloudinary_icon/e_brightness:90/o_60/c_scale,w_50/fl_layer_apply,g_south_east,x_5,y_5/a_10/q_auto/front_face.png "with_url: true, with_code: false")

In a similar way, you can [transform a video](go_media_transformations#apply_common_video_transformations).

> **Learn more about transformations**:
>
> * Read the [Transform and customize assets](image_transformations) guide to learn about the different ways to transform your assets.

> * See more examples of [media transformations](go_media_transformations) using the Cloudinary Go library.  

> * See all possible transformations in the [Transformation URL API reference](transformation_reference).

### Quick example: Get details of a single asset

The following Go example uses the Admin API [Asset](admin_api#get_details_of_a_single_resource_by_public_id) method to return details of the image with PublicID `cld-sample`:

```go
var ctx = context.Background()
resp, err := cld.Admin.Asset(ctx, admin.AssetParams{PublicID: "cld-sample"})
if err != nil {
	fmt.Println("error")
}
log.Println(resp.SecureURL)
```

Sample output:  

```json
{
  "asset_id": "bf98540caf22ed65775ee0951f4746c9",
  "public_id": "cld-sample",
  "format": "jpg",
  "version": 1719304891,
  "resource_type": "image",
  "type": "upload",
  "created_at": "2024-06-25T08:41:31Z",
  "bytes": 476846,
  "width": 1870,
  "height": 1250,
  "backup": true,
  "asset_folder": "",
  "display_name": "cld-sample",
  "url": "http://res.cloudinary.com/cld-docs/image/upload/v1719304891/cld-sample.jpg",
  "secure_url": "https://res.cloudinary.com/cld-docs/image/upload/v1719304891/cld-sample.jpg",
  "next_cursor": "497b323dcb9883a15a5e6a7cfb75d439e4de1ca882f5cbe8de6a8b322c37bdad",
  "derived": [
    {
      "transformation": "c_scale,w_500",
      "format": "jpg",
      "bytes": 22871,
      "id": "ce3d7bf3068809656dc5aa76572535da",
      "url": "http://res.cloudinary.com/cld-docs/image/upload/c_scale,w_500/v1719304891/cld-sample.jpg",
      "secure_url": "https://res.cloudinary.com/cld-docs/image/upload/c_scale,w_500/v1719304891/cld-sample.jpg"
    }
  ]
}

 ```

> **Learn more about managing assets**:
>
> * Check out the [Manage and analyze assets](asset_management) guide for all the different capabilities.

> * Get an overview of [asset management](go_asset_administration) using the Go SDK.

> * Select the **Go** tab in the [Admin API](admin_api) and [Upload API](image_upload_api_reference) references to see example code snippets.

 
## Sample projects
Take a look at the [Go sample projects][sample-projects-link] page to help you get started integrating Cloudinary into your Go application.> **TIP**: Check out our collection of [Go code explorers](code_explorers) too!

> **READING**:
>
> * Try out the Go SDK using the [quick start](go_quick_start).

> * Learn more about [uploading images and videos](go_image_and_video_upload) using the Go SDK.    

> * See examples of [media transformations](go_media_transformations) using Go code, and see our [image transformations](image_transformations) and [video transformation](video_manipulation_and_delivery) docs.   

> * Check out Cloudinary's [asset management](go_asset_administration) capabilities, for example, renaming and deleting assets, adding tags and metadata to assets, and searching for assets.

> * Stay tuned for updates by following the [Release Notes](programmable_media_release_notes) and the [Cloudinary Blog](https://cloudinary.com/blog).
