### Complete Authentication Setup Example Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md This example demonstrates a complete authentication setup using environment variables and verifies account access, lists API tokens, and checks profile settings. ```go package main import ( "context" "fmt" "log" "net/http" "os" "github.com/linode/linodego/v2" "golang.org/x/oauth2" ) func main() { // Initialize client from environment client, err := linodego.NewClientFromEnv(nil) if err != nil { log.Fatal(err) } // Verify account access account, err := client.GetAccount(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("Authenticated as: %s %s\n", account.FirstName, account.LastName) // Manage API tokens tokens, err := client.ListTokens(context.Background(), nil) if err != nil { log.Fatal(err) } fmt.Printf("Active tokens: %d\n", len(tokens)) // Check profile settings profile, err := client.GetProfile(context.Background()) if err != nil { log.Fatal(err) } fmt.Printf("2FA enabled: %v\n", profile.TwoFactorAuth) } ``` -------------------------------- ### Install linodego Source: https://github.com/linode/linodego/blob/main/README.md Install the linodego library using go get. ```sh go get -u github.com/linode/linodego/v2 ``` -------------------------------- ### Example: Configure DNS Servers for a Region Source: https://github.com/linode/linodego/blob/main/_autodocs/06_regions_and_types.md Demonstrates how to retrieve region information and print its DNS resolver addresses. ```go region, _ := client.GetRegion(ctx, "us-east") fmt.Printf("Configure DNS servers:\n") fmt.Printf(" IPv4: %s\n", region.Resolvers.IPv4) fmt.Printf(" IPv6: %s\n", region.Resolvers.IPv6) ``` -------------------------------- ### Complete Error Handling Example Source: https://github.com/linode/linodego/blob/main/_autodocs/09_error_handling.md A full example demonstrating how to handle various Linode API errors, including authentication, permissions, validation, rate limiting, and server errors, when creating a Linode instance. ```go package main import ( "context" "errors" "fmt" "log" "time" "github.com/linode/linodego/v2" ) func createInstanceWithErrorHandling(client *linodego.Client, ctx context.Context) (*linodego.Instance, error) { opts := linodego.InstanceCreateOptions{ Region: "us-east", Type: "g6-standard-1", Label: "web-server", Image: "linode/debian12", } instance, err := client.CreateInstance(ctx, opts) if err != nil { var linodeErr *linodego.Error if !errors.As(err, &linodeErr) { // Not a Linode API error return nil, fmt.Errorf("unexpected error: %w", err) } code := linodeErr.StatusCode() // Handle different error codes switch { case code == 401: return nil, fmt.Errorf("authentication failed: check your API token") case code == 403: return nil, fmt.Errorf("permission denied: you cannot create instances") case code == 400 || code == 422: // Validation error - detailed message already in error return nil, fmt.Errorf("validation failed: %s", linodeErr.Message) case code == 429: // Rate limit - retry after delay log.Println("Rate limited, retrying in 5 seconds...") time.Sleep(5 * time.Second) return createInstanceWithErrorHandling(client, ctx) case code >= 500: // Server error - retry with backoff return nil, fmt.Errorf("server error (code %d): %s", code, linodeErr.Message) default: return nil, linodeErr } } return instance, nil } func main() { client, err := linodego.NewClientFromEnv(nil) if err != nil { log.Fatal(err) } ctx := context.Background() instance, err := createInstanceWithErrorHandling(client, ctx) if err != nil { log.Fatal(err) } fmt.Printf("Created instance: %d (%s)\n", instance.ID, instance.Label) } ``` -------------------------------- ### SetRetryMaxWaitTime Example Source: https://github.com/linode/linodego/blob/main/_autodocs/01_client_initialization.md Example of setting the maximum wait time between retries to 60 seconds. ```go client.SetRetryMaxWaitTime(60 * time.Second) ``` -------------------------------- ### List Images Example Source: https://github.com/linode/linodego/blob/main/_autodocs/05_images_api.md Lists all available public and custom images. Handles pagination and filtering via ListOptions. ```go images, err := client.ListImages(ctx, nil) if err != nil { log.Fatal(err) } for _, img := range images { fmt.Printf("Image: %s (%s) - %s\n", img.ID, img.Label, img.Type) } ``` -------------------------------- ### General Usage Example Source: https://github.com/linode/linodego/blob/main/README.md Demonstrates how to initialize the Linode client with an API key and retrieve a specific Linode instance. Ensure the LINODE_TOKEN environment variable is set. ```go package main import ( "context" "fmt" "log" "net/http" "os" "github.com/linode/linodego/v2" "golang.org/x/oauth2" ) func main() { apiKey, ok := os.LookupEnv("LINODE_TOKEN") if !ok { log.Fatal("Could not find LINODE_TOKEN, please assert it is set.") } tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: apiKey}) oauth2Client := &http.Client{ Transport: &oauth2.Transport{ Source: tokenSource, }, } linodeClient, err := linodego.NewClient(oauth2Client) if err != nil { log.Fatal(err) } linodeClient.SetDebug(true) res, err := linodeClient.GetInstance(context.Background(), 4090913) if err != nil { log.Fatal(err) } fmt.Printf("%v", res) } ``` -------------------------------- ### Example: Display Placement Group Limits for a Region Source: https://github.com/linode/linodego/blob/main/_autodocs/06_regions_and_types.md Shows how to fetch region data and print placement group limits if they are defined. ```go region, _ := client.GetRegion(ctx, "us-east") if region.PlacementGroupLimits != nil { fmt.Printf("Placement Group Limits:\n") fmt.Printf(" Max groups: %d\n", region.PlacementGroupLimits.MaximumPGsPerCustomer) fmt.Printf(" Max linodes per group: %d\n", region.PlacementGroupLimits.MaximumLinodesPerPG) } ``` -------------------------------- ### SetPollDelay Example Source: https://github.com/linode/linodego/blob/main/_autodocs/01_client_initialization.md Example of setting the poll delay for WaitFor operations to 5 seconds. ```go client.SetPollDelay(5 * time.Second) ``` -------------------------------- ### List All Databases Source: https://github.com/linode/linodego/blob/main/_autodocs/10_databases_api.md Lists all databases on the account. Useful for getting an overview of existing database instances, their configurations, and status. ```go databases, err := client.ListDatabases(ctx, nil) if err != nil { log.Fatal(err) } for _, db := range databases { fmt.Printf("Database: %s (%s v%s)\n", db.Label, db.Engine, db.Version) fmt.Printf(" Status: %s\n", db.Status) fmt.Printf(" Region: %s\n", db.Region) fmt.Printf(" Cluster Size: %d nodes\n", db.ClusterSize) } ``` -------------------------------- ### Get Image Example Source: https://github.com/linode/linodego/blob/main/_autodocs/05_images_api.md Retrieves a specific image using its unique ID. Returns a 404 error if the image is not found. ```go image, err := client.GetImage(ctx, "linode/debian12") if err != nil { log.Fatal(err) } fmt.Printf("Image: %s - Vendor: %s\n", image.Label, image.Vendor) ``` -------------------------------- ### Example API Error Response Source: https://github.com/linode/linodego/blob/main/_autodocs/09_error_handling.md Illustrates the format of an example error response from the API, detailing specific field errors. ```go // Error: "[400] [disk_size] Must be at least 10 GiB; [label] Label is required" ``` -------------------------------- ### Create Linode Instance with Options Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Example of how to instantiate and populate InstanceCreateOptions to create a new Linode instance. This demonstrates setting essential parameters like region, type, label, image, SSH keys, backup enablement, and tags. ```go opts := linodego.InstanceCreateOptions{ Region: "us-east", Type: "g6-standard-2", Label: "web-server-01", Image: "linode/debian12", AuthorizedKeys: []string{"ssh-rsa AAA..."}, BackupsEnabled: true, Tags: []string{"production"}, } ``` -------------------------------- ### Auto-Pagination Example Source: https://github.com/linode/linodego/blob/main/_autodocs/08_pagination_and_filtering.md Fetch all pages automatically by passing nil or a ListOptions with page 0. All matching results across all pages are returned in a single slice. ```go instances, err := client.ListInstances(ctx, nil) // or opts := linodego.NewListOptions(0, "") instances, err := client.ListInstances(ctx, opts) ``` ```go // Get all instances regardless of count allInstances, err := client.ListInstances(ctx, nil) if err != nil { log.Fatal(err) } fmt.Printf("Total instances: %d\n", len(allInstances)) ``` -------------------------------- ### Poll for Instance Boot Event Source: https://github.com/linode/linodego/blob/main/_autodocs/11_advanced_features.md Example of polling for a specific event, such as an instance booting, using the EventPoller. Waits for the action to complete. ```go // Poll for events on an instance poller := linodego.EventPoller{ EntityID: 123, EntityType: linodego.EntityInstance, Action: linodego.ActionInstanceBoot, client: client, } // Poll until action completes err := poller.WaitForAction(ctx) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Connect to Linode Database Instance Source: https://github.com/linode/linodego/blob/main/_autodocs/10_databases_api.md Example Go code demonstrating how to connect to a Linode database instance using the linodego library and standard Go database/sql package. Ensure environment variables for authentication are set. ```go package main import ( "context" "database/sql" "log" _ "github.com/lib/pq" // PostgreSQL driver "github.com/linode/linodego/v2" ) func main() { client, _ := linodego.NewClientFromEnv(nil) ctx := context.Background() // Get database details db, err := client.GetDatabase(ctx, 123) if err != nil { log.Fatal(err) } // Extract connection info connStr := db.InstanceURI fmt.Printf("Connecting to: %s\n", db.Label) // Connect to database sqlDB, err := sql.Open("postgres", connStr) if err != nil { log.Fatal(err) } defer sqlDB.Close() // Verify connection if err := sqlDB.Ping(); err != nil { log.Fatal(err) } fmt.Println("Connected successfully") } ``` -------------------------------- ### NewClientFromEnv Source: https://github.com/linode/linodego/blob/main/_autodocs/01_client_initialization.md Creates a Client with values from environment variables and configuration files. It respects a priority order for authentication sources, starting with the LINODE_TOKEN environment variable. ```APIDOC ## NewClientFromEnv ### Description Creates a Client with values from environment variables and configuration files. ### Method `func NewClientFromEnv(hc *http.Client) (*Client, error)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **hc** (*http.Client) - Optional - HTTP client for making requests ### Returns - `*Client`: Configured client - `error`: If config file or token cannot be resolved ### Priority Order 1. `LINODE_TOKEN` environment variable (highest priority) 2. Config file at `LINODE_CONFIG` path 3. Default config paths: `~/.config/linode` or `~/.config/linode-cli` ### Request Example ```go client, err := linodego.NewClientFromEnv(nil) if err != nil { log.Fatal(err) } ``` ### Response #### Success Response - `*Client`: Configured client #### Error Response - `error`: If config file or token cannot be resolved #### Response Example None explicitly provided, but the function returns a `*Client` instance or an `error`. ``` -------------------------------- ### NewError Examples Source: https://github.com/linode/linodego/blob/main/_autodocs/09_error_handling.md Demonstrates creating linodego.Error instances from different input types like HTTP responses, Go errors, strings, and fmt.Stringers. ```go // From HTTP response httpErr := linodego.NewError(httpResponse) // From Go error goErr := linodego.NewError(fmt.Errorf("custom error")) // From string strErr := linodego.NewError("error message") ``` -------------------------------- ### Manual Pagination Example Source: https://github.com/linode/linodego/blob/main/_autodocs/08_pagination_and_filtering.md Fetch a specific page (e.g., page 2) with manual pagination. The ListOptions object is mutated by the API call to include total results and pages. ```go opts := linodego.NewListOptions(2, "") // Page 2 instances, err := client.ListInstances(ctx, opts) fmt.Printf("Total results: %d, Total pages: %d\n", opts.Results, opts.Pages) ``` -------------------------------- ### Simple Equality Filter Example Source: https://github.com/linode/linodego/blob/main/_autodocs/08_pagination_and_filtering.md Creates a filter for a specific region and applies it to list instances. Ensures only instances in 'us-east' are returned. ```go f := linodego.Filter{} f.AddField(linodego.Eq, "region", "us-east") filterStr, err := f.MarshalJSON() if err != nil { log.Fatal(err) } opts := linodego.NewListOptions(0, string(filterStr)) instances, err := client.ListInstances(ctx, opts) ``` -------------------------------- ### Get Account Information Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Retrieves the account information for the authenticated user. Use this to fetch details like name, email, and balance. ```go account, err := client.GetAccount(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Account: %s %s\n", account.FirstName, account.LastName) fmt.Printf("Email: %s\n", account.Email) fmt.Printf("Balance: $%.2f\n", account.Balance) fmt.Printf("Active Since: %v\n", account.ActiveSince) ``` -------------------------------- ### Ordering Results Example Source: https://github.com/linode/linodego/blob/main/_autodocs/08_pagination_and_filtering.md Configures sorting for API results by specifying a field and order (ascending or descending). Returns active instances ordered by creation date, newest first. ```go f := linodego.Filter{ OrderBy: "created", // Order by creation date Order: linodego.Descending, } f.AddField(linodego.Eq, "status", "active") filterStr, _ := f.MarshalJSON() opts := linodego.NewListOptions(0, string(filterStr)) instances, err := client.ListInstances(ctx, opts) ``` -------------------------------- ### Auto-Pagination for Listing Resources Source: https://github.com/linode/linodego/blob/main/_autodocs/00_index.md Retrieve all items across all pages automatically. This is the simplest way to get a complete list of resources when the total number is unknown or large. ```go // Get all results across all pages items, err := client.ListItems(ctx, nil) // or opts := linodego.NewListOptions(0, "") items, err := client.ListItems(ctx, opts) ``` -------------------------------- ### Get Account Settings Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Retrieves account-wide settings. Use this to fetch current network helper status, backup defaults, and status page subscription preferences. ```go func (c *Client) GetAccountSettings(ctx context.Context) (*AccountSettings, error) ``` -------------------------------- ### Initialize Client from Environment Variables Source: https://github.com/linode/linodego/blob/main/_autodocs/01_client_initialization.md Use NewClientFromEnv to create a client instance using environment variables and configuration files. It prioritizes LINODE_TOKEN, then config files, and finally default paths. ```Go client, err := linodego.NewClientFromEnv(nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Two-Factor Authentication Status Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Gets the current two-factor authentication status for the account. This function returns the status without enabling or disabling 2FA. ```go func (c *Client) GetTwoFactor(ctx context.Context) (*TwoFactor, error) ``` -------------------------------- ### Initialize linodego Client Source: https://github.com/linode/linodego/blob/main/_autodocs/00_index.md Demonstrates how to create a linodego client using an OAuth2 token or from environment variables. Requires importing necessary packages. ```go import ( "context" "github.com/linode/linodego/v2" "golang.org/x/oauth2" ) // Create client with OAuth2 token tokenSource := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: apiKey}) httpClient := &http.Client{ Transport: &oauth2.Transport{Source: tokenSource}, } client, err := linodego.NewClient(httpClient) // Or from environment client, err := linodego.NewClientFromEnv(nil) // Make API calls instance, err := client.GetInstance(context.Background(), 123) ``` -------------------------------- ### ConfirmTwoFactor Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Confirms 2FA setup by providing a code. After enabling 2FA and obtaining a secret, this method is used to verify the setup by submitting a code generated by the authenticator application. ```APIDOC ## ConfirmTwoFactor ### Description Confirms 2FA setup by providing a code. After enabling 2FA and obtaining a secret, this method is used to verify the setup by submitting a code generated by the authenticator application. ### Method POST ### Endpoint /profile/tfa/confirm ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **Token** (string) - Required - 6-digit code from authenticator ### Request Example { "Token": "123456" } ### Response #### Success Response (200) - **Enabled** (bool) - Indicates if 2FA is enabled - **Pending** (bool) - Indicates if 2FA setup is pending #### Response Example { "Enabled": true, "Pending": false } ``` -------------------------------- ### Client Initialization Source: https://github.com/linode/linodego/blob/main/_autodocs/COMPLETION_SUMMARY.txt Details on how to initialize the Linode Go SDK client, including factory methods, authentication patterns, and configuration options. ```APIDOC ## Client Initialization ### Description Provides methods for creating and configuring a client to interact with the Linode API. ### Methods - **NewClient()**: Creates a new Linode API client. - **NewClientFromEnv()**: Creates a new Linode API client using environment variables for configuration. ### Configuration Options - **Authentication**: Supports OAuth2 and token-based authentication. - **HTTP Client**: Options for configuring the underlying HTTP client, including URL, version, SSL, and proxies. - **Retry Configuration**: Automatic backoff strategy for retries. - **Response Caching**: Configurable response caching with a default of 15 minutes. - **Logging**: Support for debug logging and custom loggers. ``` -------------------------------- ### GetToken Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Gets details for a specific API token. ```APIDOC ## GetToken ### Description Gets details for a specific API token. ### Method GET ### Endpoint /profile/tokens/{token_id} ### Parameters #### Path Parameters - **token_id** (int) - Required - The ID of the token to retrieve. #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **ID** (int) - The unique identifier of the token. - **Label** (string) - The label of the token. - **Created** (string) - The creation date of the token. - **LastUsed** (string) - The last used date of the token. - **Scopes** (string) - The scopes assigned to the token. - **Expiry** (string) - The expiration date of the token. #### Response Example { "example": "{\"id\": 123, \"label\": \"my-token\", \"created\": \"2023-01-01T10:00:00Z\", \"last_used\": \"2023-01-01T10:00:00Z\", \"scopes\": \"*\", \"expiry\": \"2024-01-01T10:00:00Z\"}" } ``` -------------------------------- ### Initialize Client with HTTP Client Source: https://github.com/linode/linodego/blob/main/_autodocs/01_client_initialization.md Use NewClient to create a client instance with a pre-configured HTTP client. It handles response caching, default user agent, retry conditions, and loads environment variables. ```Go oauth2Client := &http.Client{ Transport: &oauth2.Transport{ Source: tokenSource, }, } client, err := linodego.NewClient(oauth2Client) if err != nil { log.Fatal(err) } ``` -------------------------------- ### GetInstance Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Gets a specific instance by ID. Returns an error if the instance is not found. ```APIDOC ## GetInstance ### Description Gets a specific instance by ID. Returns an error if the instance is not found. ### Method (Not specified, likely a SDK method) ### Endpoint (Not specified, likely a SDK method) ### Parameters #### Path Parameters - **instanceID** (int) - Required - Linode instance ID #### Query Parameters (None specified) #### Request Body (None specified) ### Request Example ```go instance, err := client.GetInstance(ctx, 4090913) if linodego.IsNotFound(err) { log.Println("Instance not found") return } if err != nil { log.Fatal(err) } fmt.Printf("Instance %s is %s\n", instance.Label, instance.Status) ``` ### Response #### Success Response - **instance** (*Instance) - The requested instance object. - **error** (error) - An error if the operation failed. #### Response Example (Not specified) ### Error Handling - Returns error with code 404 if instance not found ``` -------------------------------- ### Boot Linode Instance Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Boots an offline Linode instance. Optional boot configurations can be provided. ```go err := client.BootInstance(ctx, 123, nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get SSH Key by ID Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Retrieves a specific SSH key using its unique identifier. ```go func (c *Client) GetSSHKey(ctx context.Context, keyID int) (*SSHKey, error) ``` -------------------------------- ### GetRegion Source: https://github.com/linode/linodego/blob/main/_autodocs/06_regions_and_types.md Gets details for a specific region. This is a cached endpoint with a default expiration of 1 minute. ```APIDOC ## GetRegion ### Description Gets details for a specific region. This is a cached endpoint with a default expiration of 1 minute. ### Method GET ### Endpoint /regions/{regionID} ### Parameters #### Path Parameters - **regionID** (string) - Required - Region ID (e.g., "us-east") ### Request Example ```go region, err := client.GetRegion(ctx, "us-east") if err != nil { log.Fatal(err) } // Check if region has specific capability hasKubernetes := contains(region.Capabilities, string(linodego.CapabilityLKE)) hasManagedDB := contains(region.Capabilities, string(linodego.CapabilityDBAAS)) fmt.Printf("Region: %s\n", region.Label) fmt.Printf(" Status: %s\n", region.Status) fmt.Printf(" Kubernetes: %v\n", hasKubernetes) fmt.Printf(" Managed DB: %v\n", hasManagedDB) fmt.Printf(" DNS IPv4: %s\n", region.Resolvers.IPv4) fmt.Printf(" DNS IPv6: %s\n", region.Resolvers.IPv6) ``` ### Response #### Success Response (200) - **id** (string) - Region identifier (e.g., "us-east", "eu-west") - **country** (string) - Country code (e.g., "US", "GB") - **capabilities** ([]string) - Feature availability in region - **status** (string) - Operational status of region - **label** (string) - Human-readable region name - **site_type** (string) - Region type (core, distributed, edge) - **monitors** (RegionMonitors) - Monitoring endpoint addresses - **resolvers** (RegionResolvers) - DNS resolver addresses - **placement_group_limits** (*RegionPlacementGroupLimits) - Resource limits for this region #### Response Example ```json { "id": "us-east", "country": "US", "capabilities": [ "Linodes", "Backups", "Block Storage", "Object Storage", "Kubernetes", "Node Balancers", "Managed Databases", "VPCs", "Cloud Firewall", "Metadata", "Placement Groups", "Cloud NAT" ], "status": "ok", "label": "Newark, NJ", "site_type": "core", "monitors": { "public": "http://1.1.1.1" }, "resolvers": { "ipv4": "1.1.1.1", "ipv6": "::1" }, "placement_group_limits": {} } ``` ### Error Handling - **404** - Region not found. ``` -------------------------------- ### GetTwoFactor Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Gets two-factor authentication status. This endpoint retrieves the current status of two-factor authentication for the account. ```APIDOC ## GetTwoFactor ### Description Gets two-factor authentication status. This endpoint retrieves the current status of two-factor authentication for the account. ### Method GET ### Endpoint /profile/tfa ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - **Enabled** (bool) - Indicates if 2FA is enabled - **Pending** (bool) - Indicates if 2FA setup is pending #### Response Example { "Enabled": true, "Pending": false } ``` -------------------------------- ### Get User Profile Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Retrieves the profile of the authenticated user. Use this to fetch current user settings. ```go profile, err := client.GetProfile(ctx) if err != nil { log.Fatal(err) } fmt.Printf("Username: %s\n", profile.Username) fmt.Printf("Two-Factor Auth: %v\n", profile.TwoFactorAuth) fmt.Printf("Email: %s\n", profile.Email) ``` -------------------------------- ### GetInstanceTransfer Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Gets monthly network transfer statistics for an instance, including used, billable, and quota amounts. ```APIDOC ## GetInstanceTransfer ### Description Gets monthly network transfer statistics. ### Method GET (Assumed, as it retrieves data) ### Endpoint `/instances/{instance_id}/transfers` (Assumed based on common REST patterns) ### Parameters #### Path Parameters - **instanceID** (int) - Required - The ID of the instance to get transfer statistics for. ### Response #### Success Response (200) - **Used** (int) - Bytes consumed. - **Billable** (int) - Billable transfer in GB. - **Quota** (int) - Instance's transfer quota in GB. ### Response Example ```json { "Used": 1073741824, "Billable": 1, "Quota": 10 } ``` #### Error Handling - Returns an `error` object if the operation fails. ``` -------------------------------- ### GetType Source: https://github.com/linode/linodego/blob/main/_autodocs/06_regions_and_types.md Gets details for a specific instance type by its ID. This is a cached endpoint with a default 15-minute expiration. ```APIDOC ## GetType ### Description Gets details for a specific instance type. ### Method GET ### Endpoint /v4/linode/types/{typeID} ### Parameters #### Path Parameters - **typeID** (string) - Required - The ID of the instance type to retrieve (e.g., "g6-standard-2"). ### Response #### Success Response (200) - **id** (string) - Type identifier (e.g., "g6-standard-2"). - **label** (string) - Human-readable name. - **class** (LinodeTypeClass) - Type class (standard, highmem, gpu, dedicated, nanode). - **vcpus** (int) - Number of virtual CPUs. - **memory** (int) - RAM in MB. - **disk** (int) - Disk storage in MB. - **transfer** (int) - Network transfer quota in GB. - **gpus** (int) - Number of GPUs (if any). - **accelerated_devices** (int) - Accelerated devices count. - **price** (*LinodePrice) - Hourly and monthly pricing. - **addons** (*LinodeAddons) - Available add-ons and their prices. - **region_prices** ([]LinodeRegionPrice) - Region-specific pricing. - **successor** (string) - Type ID of successor (if deprecated). #### Error Response (404) - **errors** ([]object) - A list of errors. Contains details if the type does not exist. ### Response Example ```json { "id": "g6-standard-2", "label": "General Purpose 2", "memory": 4096, "disk": 81920, "vcpus": 2, "transfer": 1000, "class": "g6", "price": { "hourly": 0.03, "monthly": 20.0 }, "addons": { "backups": { "price": { "hourly": 0.004, "monthly": 2.0 } } }, "region_prices": [ { "id": "us-east", "hourly": 0.03, "monthly": 20.0 } ], "successor": null, "gpu_price": null, "accelerated_devices": 0 } ``` ``` -------------------------------- ### Create and Wait for Instance Source: https://github.com/linode/linodego/blob/main/_autodocs/00_index.md Create a Linode instance and wait until it reaches the 'running' state. This is useful for ensuring a resource is ready before proceeding. ```go // Create resource and wait for active state instance, _ := client.CreateInstance(ctx, opts) instance, _ = client.WaitForInstanceStatus(ctx, instance.ID, linodego.InstanceRunning) ``` -------------------------------- ### Load and Use Specific Configuration Profile Source: https://github.com/linode/linodego/blob/main/_autodocs/11_advanced_features.md Load client configuration from a specified file path and profile, or switch to use a particular profile. ```go err = client.LoadConfig(&linodego.LoadConfigOptions{ Path: "/etc/linode.conf", Profile: "staging", }) if err != nil { log.Fatal(err) } err = client.UseProfile("staging") if err != nil { log.Fatal(err) } ``` -------------------------------- ### GetInstanceMonthlyTransfer Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Gets specific monthly transfer statistics for an instance, including inbound, outbound, and total bytes transferred. ```APIDOC ## GetInstanceMonthlyTransfer ### Description Gets transfer statistics for a specific month. ### Method GET (Assumed, as it retrieves data) ### Endpoint `/instances/{instance_id}/transfers/{year}/{month}` (Assumed based on common REST patterns) ### Parameters #### Path Parameters - **instanceID** (int) - Required - The ID of the instance. - **year** (int) - Required - The year for the transfer statistics (e.g., 2024). - **month** (int) - Required - The month for the transfer statistics (1-12). ### Response #### Success Response (200) - **BytesIn** (uint64) - Inbound traffic in bytes. - **BytesOut** (uint64) - Outbound traffic in bytes. - **BytesTotal** (uint64) - Total traffic in bytes. ### Response Example ```json { "BytesIn": 536870912, "BytesOut": 536870912, "BytesTotal": 1073741824 } ``` #### Error Handling - Returns an `error` object if the operation fails. ``` -------------------------------- ### Find Cheapest Instance Type Source: https://github.com/linode/linodego/blob/main/_autodocs/06_regions_and_types.md Searches through a list of instance types to find the cheapest standard type with at least 2 vCPUs. Prints the label and monthly price of the best value type found. ```go // Find cheapest type with at least 2 vCPUs var cheapest *linodego.LinodeType types, _ := client.ListTypes(ctx, nil) for _, t := range types { if t.VCPUs >= 2 && t.Class == string(linodego.ClassStandard) { if cheapest == nil || t.Price.Monthly < cheapest.Price.Monthly { t := t // copy cheapest = &t } } } if cheapest != nil { fmt.Printf("Best value: %s ($%.2f/month)\n", cheapest.Label, cheapest.Price.Monthly) } ``` -------------------------------- ### Create a New Managed Database Source: https://github.com/linode/linodego/blob/main/_autodocs/10_databases_api.md Use this function to provision a new managed database instance. Specify all required parameters like label, engine, region, type, and cluster size. Ensure the context is properly handled. ```go db, err := client.CreateDatabase(ctx, linodego.DatabaseCreateOptions{ Label: "production-mysql", EngineID: "mysql/8.0.26", Region: "us-east", Type: "g6-nanode-1", ClusterSize: 3, // HA cluster Encrypted: true, AllowList: []string{ "192.0.2.1/32", "198.51.100.0/24", }, }) if err != nil { log.Fatal(err) } fmt.Printf("Database created: %d\n", db.ID) fmt.Printf("Connection: %s\n", db.InstanceURI) ``` -------------------------------- ### Regions and Types Source: https://github.com/linode/linodego/blob/main/_autodocs/00_index.md Functions for retrieving information about Linode regions and instance types, including listing and getting details. ```APIDOC ## Regions and Types ### Description Functions for retrieving information about Linode regions and instance types, including listing and getting details. ### Functions - `ListRegions()` - List all regions [CACHED] - `GetRegion(id)` - Get region details [CACHED] - `ListTypes()` - List instance types [CACHED] - `GetType(id)` - Get type details [CACHED] - `ListDatabaseTypes()` - List database types - `ListDatabaseEngines()` - List database engines ### Types - `Region` - Region resource - `LinodeType` - Instance type - `DatabaseType` - Database type ``` -------------------------------- ### Get Specific API Token Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Retrieves details for a specific API token by its ID. Use this to inspect a single token. ```go token, err := client.GetToken(ctx, 123) if err != nil { log.Fatal(err) } fmt.Printf("Token: %s (expires: %v)\n", token.Label, token.Expiry) ``` -------------------------------- ### BootInstance Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Boots an offline instance. This operation can be configured with optional boot settings. ```APIDOC ## BootInstance ### Description Boots an offline instance. ### Method POST ### Endpoint /instances/{instance_id}/boot ### Parameters #### Path Parameters - **instance_id** (int) - Required - The ID of the instance to boot. #### Request Body - **opts** (*InstanceBootOptions) - Optional - Boot configuration options. ### Request Example ```json { "opts": { "config_drive_iso": "path/to/iso" } } ``` ### Response #### Success Response (200) - **data** (object) - Details of the instance after booting. #### Error Response (400, 404, 500) - **errors** (array) - Description of the error. ``` -------------------------------- ### Get Specific Volume by ID Source: https://github.com/linode/linodego/blob/main/_autodocs/04_volumes_api.md Retrieves a specific volume using its unique ID. Handles not found errors gracefully. ```go volume, err := client.GetVolume(ctx, 123) if linodego.IsNotFound(err) { log.Println("Volume not found") return } if err != nil { log.Fatal(err) } fmt.Printf("Volume: %s (%d GiB)\n", volume.Label, volume.Size) ``` -------------------------------- ### List All Linode Instances Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Lists all instances accessible to the account. Supports pagination and filtering via ListOptions. Use nil for default pagination. ```go instances, err := client.ListInstances(ctx, nil) // All instances if err != nil { log.Fatal(err) } ``` ```go opts := linodego.NewListOptions(1, "") opts.PageSize = 50 instances, err := client.ListInstances(ctx, opts) fmt.Printf("Total results: %d, Pages: %d\n", opts.Results, opts.Pages) ``` -------------------------------- ### InstanceCreateOptions Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Defines the configuration options for creating a new Linode instance. It includes details such as region, type, label, image, authentication methods, backup settings, and networking options. ```APIDOC ## InstanceCreateOptions ### Description Defines the configuration options for creating a new Linode instance. It includes details such as region, type, label, image, authentication methods, backup settings, and networking options. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **Region** (string) - Required - Region ID for instance - **Type** (string) - Required - Instance type ID - **Label** (string) - Optional - Instance label - **Image** (string) - Optional - OS image ID - **RootPass** (string) - Optional - Root password (if not using AuthorizedKeys) - **AuthorizedKeys** ([]string) - Optional - SSH public keys - **BackupsEnabled** (bool) - Optional - Enable backups - **Tags** ([]string) - Optional - Organization tags - **PrivateIP** (bool) - Optional - Allocate private IP - **Booted** (*bool) - Optional - Boot instance after creation ### Request Example ```go opts := linodego.InstanceCreateOptions{ Region: "us-east", Type: "g6-standard-2", Label: "web-server-01", Image: "linode/debian12", AuthorizedKeys: []string{"ssh-rsa AAA..."}, BackupsEnabled: true, Tags: []string{"production"}, } ``` ### Response #### Success Response (200) Details about the created instance (schema not provided in source). #### Response Example (Response example not provided in source) ``` -------------------------------- ### Create Linode Instance Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Use this function to create a new Linode Instance. Ensure you provide the required Region, Type, Label, Image, and AuthorizedKeys in the InstanceCreateOptions. ```go newInstance, err := client.CreateInstance(ctx, linodego.InstanceCreateOptions{ Region: "us-east", Type: "g6-standard-1", Label: "api-server", Image: "linode/debian12", AuthorizedKeys: []string{publicKey}, }) if err != nil { log.Fatal(err) } log.Printf("Created instance: %d\n", newInstance.ID) ``` -------------------------------- ### Confirm Two-Factor Authentication Source: https://github.com/linode/linodego/blob/main/_autodocs/07_account_and_profile_api.md Confirms the setup of two-factor authentication by providing a 6-digit code. This step is required after enabling 2FA to activate it. ```go func (c *Client) ConfirmTwoFactor(ctx context.Context, opts TwoFactorConfirmOptions) (*TwoFactor, error) ``` -------------------------------- ### CreateInstance Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Creates a new Linode Instance with specified options. ```APIDOC ## CreateInstance ### Description Creates a new Linode Instance. ### Method (Not specified, likely a SDK method call) ### Endpoint (Not specified, SDK method) ### Parameters #### Path Parameters (None specified) #### Query Parameters (None specified) #### Request Body (Not specified, SDK options object) ### Request Example ```go newInstance, err := client.CreateInstance(ctx, linodego.InstanceCreateOptions{ Region: "us-east", Type: "g6-standard-1", Label: "api-server", Image: "linode/debian12", AuthorizedKeys: []string{publicKey}, }) if err != nil { log.Fatal(err) } log.Printf("Created instance: %d\n", newInstance.ID) ``` ### Response #### Success Response - **Instance** (*Instance*) - The created instance object. #### Response Example (Instance object structure not fully detailed in source, example shows ID) ``` -------------------------------- ### Image Create Options Struct Source: https://github.com/linode/linodego/blob/main/_autodocs/05_images_api.md Specifies parameters for creating a new image from an existing instance disk. Requires the instance to be offline and the disk to be ext4 or raw. ```go type ImageCreateOptions struct { DiskID int Label string Description string CloudInit bool Tags []string } ``` -------------------------------- ### Multiple Conditions (AND) Filter Example Source: https://github.com/linode/linodego/blob/main/_autodocs/08_pagination_and_filtering.md Combines multiple filter conditions using the AND operator. Returns instances that match both region and status criteria. ```go f := linodego.And("", "", &linodego.Comp{Column: "region", Operator: linodego.Eq, Value: "us-east"}, &linodego.Comp{Column: "status", Operator: linodego.Eq, Value: "running"}, ) filterStr, _ := f.MarshalJSON() opts := linodego.NewListOptions(0, string(filterStr)) instances, err := client.ListInstances(ctx, opts) ``` -------------------------------- ### Load Configuration from File Source: https://github.com/linode/linodego/blob/main/_autodocs/01_client_initialization.md Loads client configuration from an INI-formatted file. Specify the path to the config file and the profile name to use. The `SkipLoadProfile` option can prevent loading the profile after reading the config. ```go err := client.LoadConfig(&linodego.LoadConfigOptions{ Path: "/etc/linode.conf", Profile: "production", }) ``` -------------------------------- ### Compare Instance Type Pricing Across Regions Source: https://github.com/linode/linodego/blob/main/_autodocs/06_regions_and_types.md Retrieves pricing information for a specific instance type, including base hourly and monthly rates, and lists any regional price overrides. ```go // Compare pricing of a type across regions typeInfo, _ := client.GetType(ctx, "g6-standard-2") fmt.Printf("Type: %s\n", typeInfo.Label) fmt.Printf("Base pricing:\n") fmt.Printf(" Hourly: $%.3f\n", typeInfo.Price.Hourly) fmt.Printf(" Monthly: $%.2f\n", typeInfo.Price.Monthly) fmt.Printf("Regional overrides:\n") for _, rp := range typeInfo.RegionPrices { fmt.Printf(" %s: $%.3f/hr or $%.2f/mo\n", rp.ID, rp.Hourly, rp.Monthly) } ``` -------------------------------- ### Get Specific Linode Instance by ID Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Retrieves a specific Linode instance using its unique ID. Handles not found errors gracefully. ```go instance, err := client.GetInstance(ctx, 4090913) if linodego.IsNotFound(err) { log.Println("Instance not found") return } if err != nil { log.Fatal(err) } fmt.Printf("Instance %s is %s\n", instance.Label, instance.Status) ``` -------------------------------- ### Database Engine Type Constants Source: https://github.com/linode/linodego/blob/main/_autodocs/10_databases_api.md Lists the supported database engine types available for provisioning. Use these to specify the desired database engine during creation. ```go const ( DatabaseEngineTypeMySQL DatabaseEngineType = "mysql" DatabaseEngineTypePostgres DatabaseEngineType = "postgresql" ) ``` -------------------------------- ### Multiple Conditions (OR) Filter Example Source: https://github.com/linode/linodego/blob/main/_autodocs/08_pagination_and_filtering.md Combines multiple filter conditions using the OR operator. Returns instances that match either of the specified region criteria. ```go f := linodego.Or("", "", &linodego.Comp{Column: "region", Operator: linodego.Eq, Value: "us-east"}, &linodego.Comp{Column: "region", Operator: linodego.Eq, Value: "us-west"}, ) filterStr, _ := f.MarshalJSON() opts := linodego.NewListOptions(0, string(filterStr)) instances, err := client.ListInstances(ctx, opts) ``` -------------------------------- ### Get Specific Database Details Source: https://github.com/linode/linodego/blob/main/_autodocs/10_databases_api.md Retrieves details for a specific database instance using its ID. This is useful for checking the connection string and other instance-specific information. ```go db, err := client.GetDatabase(ctx, 123) if err != nil { log.Fatal(err) } fmt.Printf("Connection: %s\n", db.InstanceURI) ``` -------------------------------- ### Use List Filters for Server-Side Filtering Source: https://github.com/linode/linodego/blob/main/_autodocs/11_advanced_features.md Compares fetching all instances and filtering locally versus using server-side filtering with list filters to improve efficiency. ```go // Bad: Get all and filter locally allInstances, _ := client.ListInstances(ctx, nil) productionInstances := []linodego.Instance{} for _, inst := range allInstances { if strings.Contains(inst.Label, "production") { productionInstances = append(productionInstances, inst) } } // Good: Filter on server f := linodego.Filter{} f.AddField(linodego.Contains, "label", "production") filterStr, _ := f.MarshalJSON() opts := linodego.NewListOptions(0, string(filterStr)) productionInstances, _ := client.ListInstances(ctx, opts) ``` -------------------------------- ### List All Linode Instance Types Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Lists all available Linode Instance types. This endpoint is cached with a 15-minute default. ```go func (c *Client) ListTypes(ctx context.Context, opts *ListOptions) ([]LinodeType, error) ``` ```go types, err := client.ListTypes(ctx, nil) for _, t := range types { fmt.Printf("%s: %d vCPUs, %d GB RAM\n", t.ID, t.VCPUs, t.Memory) } ``` -------------------------------- ### Get Instance Transfer Statistics Source: https://github.com/linode/linodego/blob/main/_autodocs/03_instances_api.md Retrieves the monthly network transfer statistics for a given instance. This includes used bytes, billable transfer, and quota. ```go transfer, err := client.GetInstanceTransfer(ctx, 123) if err != nil { log.Fatal(err) } fmt.Printf("Used: %d bytes, Billable: %d GB\n", transfer.Used, transfer.Billable) ``` -------------------------------- ### Update Go Module Imports Source: https://github.com/linode/linodego/blob/main/docs/linode_v2_migration_guide.md Change import paths from 'github.com/linode/linodego' to 'github.com/linode/linodego/v2'. Run 'go get' and 'go mod tidy' to update dependencies. ```go import "github.com/linode/linodego" ``` ```go import "github.com/linode/linodego/v2" ``` ```shell go get github.com/linode/linodego/v2 go mod tidy ``` -------------------------------- ### Configure Client from API URL Source: https://github.com/linode/linodego/blob/main/_autodocs/01_client_initialization.md Parses and configures the client from a full API URL, extracting scheme, host, and API version. Returns an error if the URL is invalid or missing scheme/host. ```go client, err := initialClient.UseURL("https://api.test.linode.com/v4beta") ```