Convert Figma logo to code with AI

digitalocean logogodo

DigitalOcean Go API client

1,421
293
1,421
11

Top Related Projects

AWS SDK for the Go programming language.

This repository is for active development of the Azure SDK for Go. For consumers of the SDK we recommend visiting our public developer docs at:

Google Cloud Client Libraries for Go.

Quick Overview

Godo is the official DigitalOcean API v2 client for Go. It provides a simple and efficient way to interact with DigitalOcean's services programmatically, allowing developers to manage droplets, volumes, load balancers, and other cloud resources using Go.

Pros

  • Official library maintained by DigitalOcean, ensuring compatibility and up-to-date features
  • Comprehensive coverage of DigitalOcean's API v2 endpoints
  • Well-documented with clear examples and usage instructions
  • Supports pagination and rate limiting for efficient API usage

Cons

  • Limited to DigitalOcean's services, not suitable for multi-cloud applications
  • Requires manual error handling and type assertions in some cases
  • May require frequent updates to keep up with DigitalOcean's API changes
  • Learning curve for developers new to DigitalOcean's API structure

Code Examples

  1. Creating a new Droplet:
client := godo.NewFromToken("your-api-token")
createRequest := &godo.DropletCreateRequest{
    Name:   "example-droplet",
    Region: "nyc3",
    Size:   "s-1vcpu-1gb",
    Image: godo.DropletCreateImage{
        Slug: "ubuntu-20-04-x64",
    },
}
droplet, _, err := client.Droplets.Create(context.Background(), createRequest)
  1. Listing all Droplets:
client := godo.NewFromToken("your-api-token")
opt := &godo.ListOptions{
    Page:    1,
    PerPage: 200,
}
droplets, _, err := client.Droplets.List(context.Background(), opt)
  1. Creating a new Volume:
client := godo.NewFromToken("your-api-token")
volumeRequest := &godo.VolumeCreateRequest{
    Region:        "nyc3",
    Name:          "example-volume",
    SizeGigaBytes: 100,
}
volume, _, err := client.Storage.CreateVolume(context.Background(), volumeRequest)

Getting Started

To start using Godo, follow these steps:

  1. Install Godo using Go modules:
go get github.com/digitalocean/godo
  1. Import Godo in your Go code:
import "github.com/digitalocean/godo"
  1. Create a new client using your DigitalOcean API token:
client := godo.NewFromToken("your-api-token")
  1. Use the client to interact with DigitalOcean's API:
droplets, _, err := client.Droplets.List(context.Background(), nil)
if err != nil {
    // Handle error
}
// Use droplets

Competitor Comparisons

AWS SDK for the Go programming language.

Pros of aws-sdk-go

  • More comprehensive coverage of cloud services
  • Larger community and ecosystem
  • Extensive documentation and examples

Cons of aws-sdk-go

  • More complex and potentially overwhelming for simple use cases
  • Steeper learning curve due to the breadth of AWS services
  • Larger dependency footprint

Code Comparison

godo example:

client := godo.NewFromToken("your-api-token")
droplet, _, err := client.Droplets.Create(&godo.DropletCreateRequest{
    Name:   "example-droplet",
    Region: "nyc3",
    Size:   "s-1vcpu-1gb",
    Image:  godo.DropletCreateImage{Slug: "ubuntu-20-04-x64"},
})

aws-sdk-go example:

sess := session.Must(session.NewSessionWithOptions(session.Options{
    SharedConfigState: session.SharedConfigEnable,
}))
svc := ec2.New(sess)
result, err := svc.RunInstances(&ec2.RunInstancesInput{
    ImageId:      aws.String("ami-xxxxxxxx"),
    InstanceType: aws.String("t2.micro"),
    MinCount:     aws.Int64(1),
    MaxCount:     aws.Int64(1),
})

Both libraries provide idiomatic Go interfaces for interacting with their respective cloud platforms. aws-sdk-go offers a more extensive set of services and options, reflecting AWS's broader service offerings, while godo provides a more focused and streamlined API for DigitalOcean's services.

This repository is for active development of the Azure SDK for Go. For consumers of the SDK we recommend visiting our public developer docs at:

Pros of azure-sdk-for-go

  • Comprehensive coverage of Azure services
  • Well-documented with extensive examples
  • Regular updates and active maintenance

Cons of azure-sdk-for-go

  • Larger codebase and steeper learning curve
  • More complex setup and configuration
  • Potentially slower compilation times due to size

Code Comparison

godo example:

client := godo.NewFromToken("your-api-token")
droplet, _, err := client.Droplets.Create(&godo.DropletCreateRequest{
    Name:   "example-droplet",
    Region: "nyc3",
    Size:   "s-1vcpu-1gb",
    Image:  godo.DropletCreateImage{Slug: "ubuntu-20-04-x64"},
})

azure-sdk-for-go example:

client := compute.NewVirtualMachinesClient(subscriptionID)
client.Authorizer = authorizer
future, err := client.CreateOrUpdate(
    ctx,
    resourceGroup,
    vmName,
    compute.VirtualMachine{
        Location: to.StringPtr(location),
        VirtualMachineProperties: &compute.VirtualMachineProperties{
            HardwareProfile: &compute.HardwareProfile{
                VMSize: compute.VirtualMachineSizeTypes(vmSize),
            },
        },
    },
)

The azure-sdk-for-go example demonstrates more verbose configuration and setup compared to godo, reflecting the broader scope and complexity of Azure services. While godo provides a simpler interface for DigitalOcean-specific operations, azure-sdk-for-go offers more extensive functionality for Azure's diverse range of services.

Google Cloud Client Libraries for Go.

Pros of google-cloud-go

  • More comprehensive coverage of cloud services, offering a wider range of APIs
  • Better documentation and extensive examples for each service
  • Regular updates and active maintenance by Google's development team

Cons of google-cloud-go

  • Larger codebase and potentially steeper learning curve
  • May include unnecessary dependencies for simpler projects
  • More complex setup process compared to godo

Code Comparison

godo:

client := godo.NewFromToken("your-api-token")
droplet, _, err := client.Droplets.Create(context.Background(), &godo.DropletCreateRequest{
    Name:   "example-droplet",
    Region: "nyc3",
    Size:   "s-1vcpu-1gb",
    Image:  godo.DropletCreateImage{Slug: "ubuntu-20-04-x64"},
})

google-cloud-go:

ctx := context.Background()
client, err := compute.NewInstancesRESTClient(ctx)
if err != nil {
    // Handle error
}
instance, err := client.Insert(ctx, &computepb.InsertInstanceRequest{
    Project:  "your-project-id",
    Zone:     "us-central1-a",
    Instance: &computepb.Instance{Name: "example-instance"},
})

Both libraries provide Go clients for interacting with their respective cloud platforms. godo focuses specifically on DigitalOcean's services, while google-cloud-go covers a broader range of Google Cloud Platform services. godo tends to have a simpler API structure, making it easier to get started for DigitalOcean-specific tasks. google-cloud-go offers more flexibility and features but may require more setup and configuration.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Godo

GitHub Actions CI GoDoc

Godo is a Go client library for accessing the DigitalOcean V2 API.

You can view the client API docs here: http://godoc.org/github.com/digitalocean/godo

You can view DigitalOcean API docs here: https://docs.digitalocean.com/reference/api/api-reference/

Install

go get github.com/digitalocean/godo@vX.Y.Z

where X.Y.Z is the version you need.

or

go get github.com/digitalocean/godo

for non Go modules usage or latest version.

Usage

import "github.com/digitalocean/godo"

Create a new DigitalOcean client, then use the exposed services to access different parts of the DigitalOcean API.

Authentication

Currently, Personal Access Token (PAT) is the only method of authenticating with the API. You can manage your tokens at the DigitalOcean Control Panel Applications Page.

You can then use your token to create a new client:

package main

import (
    "github.com/digitalocean/godo"
)

func main() {
    client := godo.NewFromToken("my-digitalocean-api-token")
}

If you need to provide a context.Context to your new client, you should use godo.NewClient to manually construct a client instead.

Examples

To create a new Droplet:

dropletName := "super-cool-droplet"

createRequest := &godo.DropletCreateRequest{
    Name:   dropletName,
    Region: "nyc3",
    Size:   "s-1vcpu-1gb",
    Image: godo.DropletCreateImage{
        Slug: "ubuntu-20-04-x64",
    },
}

ctx := context.TODO()

newDroplet, _, err := client.Droplets.Create(ctx, createRequest)

if err != nil {
    fmt.Printf("Something bad happened: %s\n\n", err)
    return err
}

Pagination

If a list of items is paginated by the API, you must request pages individually. For example, to fetch all Droplets:

func DropletList(ctx context.Context, client *godo.Client) ([]godo.Droplet, error) {
    // create a list to hold our droplets
    list := []godo.Droplet{}

    // create options. initially, these will be blank
    opt := &godo.ListOptions{}
    for {
        droplets, resp, err := client.Droplets.List(ctx, opt)
        if err != nil {
            return nil, err
        }

        // append the current page's droplets to our list
        list = append(list, droplets...)

        // if we are at the last page, break out the for loop
        if resp.Links == nil || resp.Links.IsLastPage() {
            break
        }

        page, err := resp.Links.CurrentPage()
        if err != nil {
            return nil, err
        }

        // set the page we want for the next request
        opt.Page = page + 1
    }

    return list, nil
}

Some endpoints offer token based pagination. For example, to fetch all Registry Repositories:

func ListRepositoriesV2(ctx context.Context, client *godo.Client, registryName string) ([]*godo.RepositoryV2, error) {
    // create a list to hold our registries
    list := []*godo.RepositoryV2{}

    // create options. initially, these will be blank
    opt := &godo.TokenListOptions{}
    for {
        repositories, resp, err := client.Registry.ListRepositoriesV2(ctx, registryName, opt)
        if err != nil {
            return nil, err
        }

        // append the current page's registries to our list
        list = append(list, repositories...)

        // if we are at the last page, break out the for loop
        if resp.Links == nil || resp.Links.IsLastPage() {
            break
        }

        // grab the next page token
        nextPageToken, err := resp.Links.NextPageToken()
        if err != nil {
            return nil, err
        }

        // provide the next page token for the next request
        opt.Token = nextPageToken
    }

    return list, nil
}

Automatic Retries and Exponential Backoff

The Godo client can be configured to use automatic retries and exponentional backoff for requests that fail with 429 or 500-level response codes via go-retryablehttp. To configure Godo to enable usage of go-retryablehttp, the RetryConfig.RetryMax must be set.

tokenSrc := oauth2.StaticTokenSource(&oauth2.Token{
    AccessToken: "dop_v1_xxxxxx",
})

oauth_client := oauth2.NewClient(oauth2.NoContext, tokenSrc)

waitMax := godo.PtrTo(6.0)
waitMin := godo.PtrTo(3.0)

retryConfig := godo.RetryConfig{
    RetryMax:     3,
    RetryWaitMin: waitMin,
    RetryWaitMax: waitMax,
}

client, err := godo.New(oauth_client, godo.WithRetryAndBackoffs(retryConfig))

Please refer to the RetryConfig Godo documentation for more information.

Versioning

Each version of the client is tagged and the version is updated accordingly.

To see the list of past versions, run git tag.

Documentation

For a comprehensive list of examples, check out the API documentation.

For details on all the functionality in this library, see the GoDoc documentation.

Contributing

We love pull requests! Please see the contribution guidelines.