godo Go Client Library

repository·main·Indexed 23 days ago

https://github.com/digitalocean/godo

A Go client library for interacting with the DigitalOcean V2 API, providing support for infrastructure management (Droplets, Kubernetes, App Platform) and the Gradient AI Platform. Features include support for page-based and token-based pagination, automatic retries with exponential backoff via go-retryablehttp, and specialized clients for Agent Inference.

Tokens
48.2K
Snippets
81
Records
299
Agent score
81%

What's inside godo

  1. Handle Pagination in API responses

    main

    DigitalOcean API results are often paginated. There are two main patterns for handling this:

    1. Page-based Pagination

    Used by endpoints like Droplets.List. You iterate using ListOptions and check resp.Links.IsLastPage(). To get the next page, use resp.Links.CurrentPage() and increment the opt.Page value.

    2. Token-based Pagination

    Used by endpoints like Registry.ListRepositoriesV2. You iterate using TokenListOptions. Instead of an integer page number, you retrieve the next token via resp.Links.NextPageToken() and assign it to opt.Token for the subsequent request.

    // Example: Page-based pagination for Droplets
    opt := &godo.ListOptions{}
    for {
        droplets, resp, err := client.Droplets.List(ctx, opt)
        if err != nil {
            return nil, err
        }
        list = append(list, droplets...)
    
        if resp.Links == nil || resp.Links.IsLastPage() {
            break
        }
    
        page, err := resp.Links.CurrentPage()
        if err != nil {
            return nil, err
        }
        opt.Page = page + 1
    }
    
    // Example: Token-based pagination for Registry
    opt := &godo.TokenListOptions{}
    for {
        repositories, resp, err := client.Registry.ListRepositoriesV2(ctx, registryName, opt)
        if err != nil {
            return nil, err
        }
        list = append(list, repositories...)
    
        if resp.Links == nil || resp.Links.IsLastPage() {
            break
        }
    
        nextPageToken, err := resp.Links.NextPageToken()
        if err != nil {
            return nil, err
        }
        opt.Token = nextPageToken
    }
  2. Authenticate with DigitalOcean API

    main

    Create a new client using godo.NewFromToken.

    Important Note on Credentials:

    • For Infrastructure APIs (Droplets, Kubernetes, etc.), use a standard DigitalOcean Personal Access Token (PAT).
    • For Inference APIs (Chat, Models, etc.), you must use either a PAT with full access scope or a Gradient Model Access Key.

    If you need to provide a context.Context during client construction, use godo.NewClient instead of godo.NewFromToken.

    package main
    
    import (
        "github.com/digitalocean/godo"
        "os"
    )
    
    func main() {
        // Using a full-access PAT
        client := godo.NewFromToken(os.Getenv("DIGITALOCEAN_TOKEN"))
    
        // OR using a Gradient model access key
        // client := godo.NewFromToken(os.Getenv("MODEL_ACCESS_KEY"))
    }
  3. Pagination with `ListOptions` and `TokenListOptions`

    main

    Many list methods in godo support pagination using one of two patterns:

    1. Page-based pagination: Use ListOptions to specify the Page and PerPage parameters.
    2. Token-based pagination: Use TokenListOptions to specify a Page and a Token (retrieved from the last set of results) to fetch the next set of results. Token-based pagination is generally faster than incrementing page numbers.
  4. Configure Automatic Retries and Exponential Backoff

    main

    The Godo client can automatically retry requests that fail with 429 (Too Many Requests) or 500-level error codes using go-retryablehttp. To enable this, you must provide a RetryConfig where RetryMax is set to a value greater than 0.

    Use godo.WithRetryAndBackoffs(retryConfig) when constructing the client with godo.New.

    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))
  5. Understand DeploymentPhase and DeploymentCauseDetailsType

    main

    When monitoring deployments in the App Platform, you can track their lifecycle and the reason they were triggered.

    Deployment Phases (DeploymentPhase):

    • PENDING_BUILD: Waiting for build resources.
    • BUILDING: Currently building.
    • PENDING_DEPLOY: Build finished, waiting to deploy.
    • DEPLOYING: Deploying containers/assets.
    • ACTIVE: Successfully running.
    • SUPERSEDED: Replaced by a newer deployment.
    • ERROR: Deployment failed.
    • CANCELED: Deployment was manually stopped.

    Deployment Causes (DeploymentCauseDetailsType):

    • MANUAL: Created by a user.
    • DEPLOY_ON_PUSH: Triggered by a Git push hook.
    • MAINTENANCE: Triggered by DigitalOcean maintenance.
    • MANUAL_ROLLBACK: Manually triggered rollback.
    • AUTO_ROLLBACK: Automatic rollback due to failure.
    • UPDATE_DATABASE_TRUSTED_SOURCES: Triggered by database configuration changes.
    • AUTOSCALED: Triggered by the autoscaler.
  6. Understand MicroDroplet lifecycle states

    main

    A MicroDroplet moves through various lifecycle states. You can monitor the State field of a MicroDroplet object to understand its current status.

    Possible MicroDropletState values:

    • MicroDropletStateUnknown: "unknown"
    • MicroDropletStateCreating: "creating"
    • MicroDropletStateRunning: "running"
    • MicroDropletStatePausing: "pausing"
    • MicroDropletStatePaused: "paused"
    • MicroDropletStateResuming: "resuming"
    • MicroDropletStateTerminating: "terminating"
    • MicroDropletStateTerminated: "terminated"
    • MicroDropletStateFailed: "failed"
  7. Understand the difference between RegistryService and RegistriesService

    main

    The godo library provides two interfaces for managing Container Registry resources:

    1. RegistryService: The legacy interface for managing a single registry. It is being deprecated.
    2. RegistriesService: The new interface designed for the multi-registry Open Beta API. This allows managing multiple named registries.

    When building new integrations, you should use RegistriesService to support multiple registries. Most methods in RegistriesService require a registry name parameter to specify which registry the action applies to, whereas RegistryService methods often act on the default registry context.

  8. Manage batch inference jobs with BatchInferenceService

    main

    The BatchInferenceService interface allows you to manage batch inference jobs via the inference proxy at inference.do-ai.run. The workflow typically involves three main steps:

    1. Prepare the input file: Call CreatePresignedUploadURL to get a unique UploadURL and FileID.
    2. Upload the data: Use UploadInputFile to upload your JSONL content to the provided UploadURL.
    3. Run the job: Call CreateJob using the FileID obtained in step 1.

    You can then monitor the job using GetJob or ListJobs, cancel it with CancelJob, and retrieve the final results using GetJobResult once ResultAvailable is true.

  9. Handle streaming responses with InferenceStream

    main

    The InferenceStream is the underlying mechanism for all streaming services in the inference API. It wraps an SSE (Server-Sent Events) reader.

    When using services like ChatCompletionService.NewStreaming, ImageGenerationService.GenerateStreaming, or MessageService.NewStreaming, you are interacting with a typed wrapper around this stream.

    Critical: You must always call .Close() on the stream (or the typed wrapper) to ensure the underlying HTTP response body is released.

  10. Configure App Platform Autoscaling

    main

    You can configure autoscaling for components within an app using AppAutoscalingSpec. This allows you to define minimum and maximum instance counts and set target metrics for scaling.

    Supported Metrics

    • CPU: Target average CPU utilization percentage (AppAutoscalingSpecMetricCPU).
    • Requests Per Second: Target number of requests per second per instance (AppAutoscalingSpecMetricRequestsPerSecond).
    • Request Duration: Target p95 request duration in milliseconds (AppAutoscalingSpecMetricRequestDuration).
  11. Identify Images and SSH Keys in Create Requests

    main

    When creating Droplets, certain fields use specialized types to allow for flexible identification:

    • DropletCreateImage: Identifies an image. It prefers a Slug if provided; otherwise, it uses the ID.
    • DropletCreateSSHKey: Identifies an SSH key. It prefers a Fingerprint if provided; otherwise, it uses the ID.
    • DropletCreateVolume: Identifies a volume. It prefers an ID over the Name (Note: Name is deprecated).
    type DropletCreateImage struct {
    	ID   int
    	Slug string
    }
    
    type DropletCreateSSHKey struct {
    	ID          int
    	Fingerprint string
    }
    
    type DropletCreateVolume struct {
    	ID string
    	// Deprecated: You must pass the volume's ID when creating a Droplet.
    	Name string
    }