### Complete Server Creation Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/QUICKSTART.md This Go program demonstrates the full lifecycle of creating a server, from client initialization to waiting for the server to become active. It requires authentication and a valid project setup. ```go package main import ( "log" "os" "github.com/cherryservers/cherrygo/v3" ) func main() { // 1. Create client client, err := cherrygo.NewClient() if err != nil { log.Fatal("Failed to create client:", err) } // 2. Get team teams, _, err := client.Teams.List(nil) if err != nil { log.Fatal("Failed to list teams:", err) } if len(teams) == 0 { log.Fatal("No teams found") } teamID := teams[0].ID log.Printf("Using team: %s", teams[0].Name) // 3. Get project projects, _, err := client.Projects.List(teamID, nil) if err != nil { log.Fatal("Failed to list projects:", err) } if len(projects) == 0 { log.Fatal("No projects found") } projectID := projects[0].ID log.Printf("Using project: %s", projects[0].Name) // 4. Get plans plans, _, err := client.Plans.List(teamID, nil) if err != nil { log.Fatal("Failed to list plans:", err) } if len(plans) == 0 { log.Fatal("No plans available") } planSlug := plans[0].Slug log.Printf("Using plan: %s", plans[0].Name) // 5. Get images images, _, err := client.Images.List(planSlug, nil) if err != nil { log.Fatal("Failed to list images:", err) } if len(images) == 0 { log.Fatal("No images available") } imageSlug := images[0].Slug log.Printf("Using image: %s", images[0].Name) // 6. Get regions regions, _, err := client.Regions.List(nil) if err != nil { log.Fatal("Failed to list regions:", err) } if len(regions) == 0 { log.Fatal("No regions available") } regionSlug := regions[0].Slug log.Printf("Using region: %s", regions[0].Name) // 7. Create server log.Println("Creating server...") server, _, err := client.Servers.Create(&cherrygo.CreateServer{ ProjectID: projectID, Plan: planSlug, Region: regionSlug, Image: imageSlug, Hostname: "demo-server", }) if err != nil { log.Fatal("Failed to create server:", err) } log.Printf("Server created: ID=%d, Hostname=%s", server.ID, server.Hostname) // 8. Wait for provisioning log.Println("Waiting for server to be ready...") for { server, _, err := client.Servers.Get(server.ID, nil) if err != nil { log.Fatal("Failed to get server:", err) } log.Printf("Status: %s", server.Status) if server.Status == "active" { break } } log.Printf("Server is ready!") log.Printf("Login as: %s@%s", server.Username, server.Hostname) log.Printf("Password: %s", server.Password) } ``` -------------------------------- ### Example: Get Plan by Slug Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/plans.md Demonstrates how to retrieve a plan's information using its human-readable slug. ```go plan, _, err := client.Plans.GetBySlug("baremetal_0", nil) if err != nil { log.Fatal(err) } log.Println("Plan name:", plan.Name) log.Println("CPU name:", plan.Specs.Cpus.Name) log.Println("CPU frequency:", plan.Specs.Cpus.Frequency, plan.Specs.Cpus.Unit) ``` -------------------------------- ### Example: Get Plan by ID Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/plans.md Shows how to fetch a plan's details using its unique numeric identifier. ```go plan, _, err := client.Plans.GetByID(1, nil) if err != nil { log.Fatal(err) } log.Println("Plan:", plan.Name) log.Println("Available regions:", len(plan.AvailableRegions)) ``` -------------------------------- ### Get User by ID Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/users.md Example demonstrating how to fetch details for a specific user using their ID. Includes error handling for the API request. ```go user, _, err := client.Users.Get(456, nil) if err != nil { log.Fatal(err) } log.Printf("User: %s %s", user.FirstName, user.LastName) log.Printf("Email: %s (verified: %v)", user.Email, user.EmailVerified) ``` -------------------------------- ### Create Project Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/projects.md Creates a new project with a specified name and BGP enabled status. ```go newProject, _, err := client.Projects.Create(teamID, &cherrygo.CreateProject{ Name: "Production Servers", Bgp: true, }) if err != nil { log.Fatal(err) } log.Println("Created project:", newProject.ID, newProject.Name) ``` -------------------------------- ### Get Project Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/projects.md Retrieves a specific project by its ID and logs its name and BGP status. ```go project, _, err := client.Projects.Get(456, nil) if err != nil { log.Fatal(err) } log.Println("Project:", project.Name) log.Println("BGP Enabled:", project.Bgp.Enabled) ``` -------------------------------- ### Get Current User Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/users.md Example of how to retrieve and display information for the currently authenticated user. Handles potential errors during the API call. ```go user, _, err := client.Users.CurrentUser(nil) if err != nil { log.Fatal(err) } log.Printf("Logged in as: %s %s (%s)\n", user.FirstName, user.LastName, user.Email) log.Printf("Email verified: %v\n", user.EmailVerified) ``` -------------------------------- ### Install Cherrygo Go Library Source: https://github.com/cherryservers/cherrygo/blob/master/README.md Add the Cherrygo library as a dependency to your Go project using the go get command. ```bash go get github.com/cherryservers/cherrygo/v3 ``` -------------------------------- ### List Projects Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/projects.md Demonstrates how to list all projects for a given team and log the total count and project details. ```go projects, resp, err := client.Projects.List(teamID, nil) if err != nil { log.Fatal(err) } log.Println("Total projects:", resp.Meta.Total) for _, project := range projects { log.Println(project.ID, project.Name) } ``` -------------------------------- ### List Servers with a Limit Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/configuration.md Example of using GetOptions to limit the number of servers returned to 50. ```go opts := &cherrygo.GetOptions{ Limit: 50, } servers, _, err := client.Servers.List(projectID, opts) ``` -------------------------------- ### NewClient Initialization Examples Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/client.md Demonstrates how to initialize a new API client, either by relying on the CHERRY_AUTH_TOKEN environment variable or by explicitly providing an authentication token. ```go package main import ( "log" "github.com/cherryservers/cherrygo/v3" ) func main() { // Using environment variable CHERRY_AUTH_TOKEN client, err := cherrygo.NewClient() if err != nil { log.Fatal(err) } // Or with explicit token client, err := cherrygo.NewClient( cherrygo.WithAuthToken("your-api-token"), ) if err != nil { log.Fatal(err) } } ``` -------------------------------- ### List Servers with Limit and Offset for Pagination Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/configuration.md Example demonstrating pagination by skipping the first 20 servers and retrieving the next 10. ```go opts := &cherrygo.GetOptions{ Limit: 10, Offset: 20, // Skip first 20, get next 10 } servers, _, err := client.Servers.List(projectID, opts) ``` -------------------------------- ### Create Server with Specific Image Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/images.md This example demonstrates the workflow of first listing available images, then finding a specific image slug (e.g., Ubuntu 20.04), and finally using that slug to create a new server. ```go // First check available images images, _, err := client.Images.List("baremetal_0", nil) if err != nil { log.Fatal(err) } // Find Ubuntu 20.04 image var ubuntuImage string for _, img := range images { if strings.Contains(img.Slug, "ubuntu_20") { ubuntuImage = img.Slug break } } if ubuntuImage == "" { log.Fatal("Ubuntu 20.04 not available for this plan") } // Create server with the image server, _, err := client.Servers.Create(&cherrygo.CreateServer{ ProjectID: projectID, Plan: "baremetal_0", Region: "eu_nord_1", Image: ubuntuImage, Hostname: "web-server-01", }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Example: List Global and Team Plans Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/plans.md Demonstrates how to list all available global plans and how to list plans specific to a team by providing a teamID. ```go // List global plans plans, _, err := client.Plans.List(0, nil) if err != nil { log.Fatal(err) } for _, plan := range plans { log.Printf("%s: %d vCPU, %d GB RAM", plan.Name, plan.Specs.Cpus.Count, plan.Specs.Memory.Total) } // List team-specific plans teamPlans, _, err := client.Plans.List(teamID, nil) if err != nil { log.Fatal(err) } ``` -------------------------------- ### List Servers with Specific Fields Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/configuration.md Example of using GetOptions to request only 'id', 'name', and 'state' fields for servers. ```go opts := &cherrygo.GetOptions{ Fields: []string{"id", "name", "state"}, } servers, _, err := client.Servers.List(projectID, opts) ``` -------------------------------- ### WithHTTPClient Option Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/client.md Illustrates how to provide a custom http.Client instance to the NewClient function for advanced configuration like timeouts. ```go customHTTPClient := &http.Client{ Timeout: time.Duration(30 * time.Second), } client, err := cherrygo.NewClient( cherrygo.WithAuthToken("token"), cherrygo.WithHTTPClient(customHTTPClient), ) ``` -------------------------------- ### Power On Server Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/servers.md Powers on a specified server. Use this when a server needs to be started. ```go server, _, err := client.Servers.PowerOn(serverID) if err != nil { log.Fatal(err) } ``` -------------------------------- ### WithAuthToken Option Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/client.md Shows how to use the WithAuthToken client option to set a specific API token during client initialization. ```go client, err := cherrygo.NewClient( cherrygo.WithAuthToken("4bdc0acb8f7af4bdc0acb8f7afe78522e6dae9b7e03b0e78522e6dae9b7e03b0"), ) ``` -------------------------------- ### Get Team by ID Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/teams.md Retrieves a specific team by its ID and logs its name and credit details. Use when you need to fetch a single team's information. ```go team, _, err := client.Teams.Get(123, nil) if err != nil { log.Fatal(err) } log.Println("Team:", team.Name) log.Println("Account Credit:", team.Credit.Account.Remaining, team.Credit.Account.Currency) log.Println("Promo Credit:", team.Credit.Promo.Remaining, team.Credit.Promo.Currency) ``` -------------------------------- ### Create Team Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/teams.md Creates a new team with specified name, type, and currency. Use when provisioning a new team resource. ```go newTeam, _, err := client.Teams.Create(&cherrygo.CreateTeam{ Name: "My New Team", Type: "business", Currency: "USD", }) if err != nil { log.Fatal(err) } log.Println("Created team:", newTeam.ID, newTeam.Name) ``` -------------------------------- ### WithURL Option Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/client.md Demonstrates using the WithURL option to specify a custom API endpoint URL for the client. ```go client, err := cherrygo.NewClient( cherrygo.WithAuthToken("token"), cherrygo.WithURL("https://custom.api.example.com/v1/"), ) ``` -------------------------------- ### Apply Query Options for List Methods Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/INDEX.md Use GetOptions to filter and paginate results when calling List methods. This example shows how to set limit, offset, and fields. ```go opts := &cherrygo.GetOptions{ Limit: 50, Offset: 0, Fields: []string{"id", "name"}, } servers, resp, err := client.Servers.List(projectID, opts) log.Println("Total:", resp.Meta.Total) ``` -------------------------------- ### Delete Project Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/projects.md Deletes a project by its ID and logs a success message upon successful deletion. ```go _, err := client.Projects.Delete(456) if err != nil { log.Fatal(err) } log.Println("Project deleted successfully") ``` -------------------------------- ### Update Project Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/projects.md Updates an existing project's name and BGP status. Only provided fields are updated. ```go newName := "Staging Servers" enableBgp := true updated, _, err := client.Projects.Update(456, &cherrygo.UpdateProject{ Name: &newName, Bgp: &enableBgp, }) if err != nil { log.Fatal(err) } log.Println("Project updated:", updated.Name) ``` -------------------------------- ### List Teams Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/teams.md Retrieves all teams for the current user and logs their total count and names. Use when you need to fetch a collection of teams. ```go teams, resp, err := client.Teams.List(nil) if err != nil { log.Fatal(err) } log.Println("Total teams:", resp.Meta.Total) for _, team := range teams { log.Println(team.ID, team.Name) } ``` -------------------------------- ### SSH Key Format Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/ssh-keys.md Illustrates the expected OpenSSH format for public SSH keys, commonly used for authentication. ```text ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQC7... user@hostname ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIBk... user@hostname ``` -------------------------------- ### Route Floating IP to Subnet Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/ip-addresses.md Shows how to route a floating IP address to a subnet. This is a common pattern for high availability. ```go _, err := client.IPAddresses.Assign(floatingIP, &cherrygo.AssignIPAddress{ IpID: subnetIP, // e.g., "192.168.1.0/24" }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Available OS Options for a Plan Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/images.md Retrieves and logs the names of operating systems available for a given plan. This is a common use case for user-facing applications. ```go images, _, err := client.Images.List("baremetal_0", nil) if err != nil { log.Fatal(err) } log.Printf("Available operating systems for baremetal_0 plan:\n") for _, image := range images { log.Printf(" - %s\n", image.Name) } ``` -------------------------------- ### WithUserAgent Option Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/client.md Shows how to set a custom user agent string for API requests using the WithUserAgent option. ```go client, err := cherrygo.NewClient( cherrygo.WithAuthToken("token"), cherrygo.WithUserAgent("MyApp/1.0"), ) ``` -------------------------------- ### Get available images for a plan Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/plans.md Retrieves a specific plan's details to list all available software/OS images for that plan. ```APIDOC ## Get Plan by Slug (for Software Images) ### Description Retrieves a specific plan's details to list all available software/OS images that can be deployed with this plan. ### Method GET ### Endpoint /plans/{slug} ### Parameters #### Path Parameters - **slug** (string) - Required - The unique identifier (slug) of the plan. ### Response #### Success Response (200) - **plan** (object) - The plan object with details. - **Name** (string) - The name of the plan. - **Softwares** (array of objects) - **Image** (object) - **Name** (string) - Human-readable image name. - **Slug** (string) - Image identifier for server creation. ### Request Example ```go plan, _, err := client.Plans.GetBySlug("baremetal_0", nil) if err != nil { log.Fatal(err) } fmt.Println("Available OS images for", plan.Name + ":") for _, software := range plan.Softwares { fmt.Printf(" - %s (%s)\n", software.Image.Name, software.Image.Slug) } ``` ``` -------------------------------- ### API Call with Custom Query Parameters Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/configuration.md Example of using GetOptions to include a custom filter parameter in the API request. ```go opts := &cherrygo.GetOptions{ QueryParams: map[string]string{ "custom_filter": "value", }, } ``` -------------------------------- ### Handle Validation Errors (400) Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/errors.md Example of a validation error (400) due to a missing required field in a server creation request. ```Go // Missing required Region field server, _, err := client.Servers.Create(&cherrygo.CreateServer{ ProjectID: projectID, Plan: "baremetal_0", // Missing Region - will get 400 error }) if err != nil { // Error response from API: region is required (error code: 400) } ``` -------------------------------- ### Verify User Credentials Usage Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/users.md Example for verifying user credentials by checking email verification status after authentication. Returns an error if authentication fails or email is not verified. ```go user, _, err := client.Users.CurrentUser(nil) if err != nil { return fmt.Errorf("authentication failed: %v", err) } if !user.EmailVerified { return fmt.Errorf("email not verified: %s", user.Email) } log.Printf("Authenticated as: %s", user.Email) ``` -------------------------------- ### Handle Timeout Errors Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/errors.md Configure a custom HTTP client with a timeout to catch network timeout errors. This example sets a 5-second timeout for all requests. ```Go customHTTPClient := &http.Client{ Timeout: time.Duration(5 * time.Second), } client, err := cherrygo.NewClient( cherrygo.WithAuthToken("token"), cherrygo.WithHTTPClient(customHTTPClient), ) // If request takes > 5 seconds, will get timeout error servers, _, err := client.Servers.List(projectID, nil) if err != nil { // err might be: "context deadline exceeded" } ``` -------------------------------- ### Create a Server Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/QUICKSTART.md Create a new server instance using the selected project, plan, region, and image. A hostname is specified for the new server. ```go server, _, err := client.Servers.Create(&cherrygo.CreateServer{ ProjectID: projectID, Plan: planSlug, Region: regionSlug, Image: imageSlug, Hostname: "my-server", }) if err != nil { log.Fatal(err) } log.Printf("Server created: %s (ID: %d)", server.Hostname, server.ID) ``` -------------------------------- ### CherryGo Client Initialization with Authentication Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/errors.md Demonstrates how to initialize the CherryGo client, handling cases where the authentication token is missing. It shows both environment variable and option-based token provision. ```Go client, err := cherrygo.NewClient() if err != nil { // err.Error() == "auth token must be provided as parameter of environment variable CHERRY_AUTH_TOKEN" } ``` ```Go // Option 1: Set environment variable os.Setenv("CHERRY_AUTH_TOKEN", "your-token") client, err := cherrygo.NewClient() // Option 2: Use WithAuthToken option client, err := cherrygo.NewClient( cherrygo.WithAuthToken("your-token"), ) ``` -------------------------------- ### Get Region BGP Details Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/regions.md Fetches a specific region and logs its BGP Autonomous System Number (ASN) and router hostnames. This example shows how to access nested BGP data from a Region object. ```go region, _, err := client.Regions.Get("eu_nord_1", nil) if err != nil { log.Fatal(err) } log.Printf("Region: %s\n", region.Name) log.Printf("BGP ASN: %d\n", region.BGP.Asn) log.Println("BGP Routers:") for _, host := range region.BGP.Hosts { log.Printf(" - %s\n", host) } ``` -------------------------------- ### Get Method Signature Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/users.md Signature for the Get method, used to retrieve information about a specific user by their ID. ```go func (s *UsersClient) Get(userID int, opts *GetOptions) (User, *Response, error) ``` -------------------------------- ### Create a New Server Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/servers.md Orders a new server instance with specified configuration. This method requires project ID, plan, and region. Optional parameters include image, hostname, SSH keys, and more. ```go newServer, _, err := client.Servers.Create(&cherrygo.CreateServer{ ProjectID: projectID, Plan: "baremetal_0", Region: "eu_nord_1", Image: "ubuntu_22_04", Hostname: "web-server-01", SSHKeys: []string{"key1", "key2"}, }) if err != nil { log.Fatal(err) } log.Printf("Created server: %d - %s", newServer.ID, newServer.Name) ``` -------------------------------- ### PlansService Interface Definition Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/plans.md Defines the interface for the PlansService, outlining methods for listing, getting by slug, and getting by ID. ```go type PlansService interface { List(teamID int, opts *GetOptions) ([]Plan, *Response, error) GetBySlug(slug string, opts *GetOptions) (Plan, *Response, error) GetByID(id int, opts *GetOptions) (Plan, *Response, error) } ``` -------------------------------- ### Get Project Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/projects.md Retrieves a specific project by its ID. Supports query options. ```APIDOC ## Get Project ### Description Retrieves a specific project by its ID. Supports query options. ### Method GET ### Endpoint `/projects/{projectID}` (Assumed based on common REST patterns and `Get` method signature) ### Parameters #### Path Parameters - **projectID** (int) - Yes - The project ID to retrieve #### Query Parameters - **opts** (*GetOptions) - No - Query options ### Response #### Success Response (200) - **Project** - Project object - ***Response** - Response metadata ### Response Example ```json { "id": 456, "name": "Specific Project", "bgp": { "enabled": true }, "response": {} } ``` ``` -------------------------------- ### List Available OS Images for a Plan Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/images.md Demonstrates how to fetch all available OS images for a specified plan. Useful for displaying options to users or for programmatic selection. ```go images, _, err := client.Images.List("baremetal_0", nil) if err != nil { log.Fatal(err) } log.Println("Available images for baremetal_0:") for _, image := range images { log.Printf(" %s (%s)", image.Name, image.Slug) } ``` -------------------------------- ### Initialize Client and List Teams Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/README.md Demonstrates how to initialize the CherryGo client using an environment variable for authentication and then list all available teams. ```go package main import ( "log" "github.com/cherryservers/cherrygo/v3" ) func main() { // Initialize client (uses CHERRY_AUTH_TOKEN env var) client, err := cherrygo.NewClient() if err != nil { log.Fatal(err) } // List teams teams, resp, err := client.Teams.List(nil) if err != nil { log.Fatal(err) } log.Printf("Found %d teams\n", resp.Meta.Total) for _, team := range teams { log.Printf("- %s (ID: %d)\n", team.Name, team.ID) } } ``` -------------------------------- ### Delete Team Example Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/teams.md Deletes a team by its ID. Use when a team is no longer needed. ```go _, err := client.Teams.Delete(123) if err != nil { log.Fatal(err) } log.Println("Team deleted successfully") ``` -------------------------------- ### List All Available Plans and Specs Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/plans.md Iterates through all available plans, printing their details including CPUs, RAM, storage, and regional availability. Requires the CherryGo client to be initialized. ```go plans, _, err := client.Plans.List(0, nil) if err != nil { log.Fatal(err) } for _, plan := range plans { fmt.Printf("Plan: %s (%s)\n", plan.Name, plan.Slug) fmt.Printf(" CPUs: %d x %s @ %.1f%s\n", plan.Specs.Cpus.Count, plan.Specs.Cpus.Name, plan.Specs.Cpus.Frequency, plan.Specs.Cpus.Unit) fmt.Printf(" RAM: %d %s\n", plan.Specs.Memory.Total, plan.Specs.Memory.Unit) for _, storage := range plan.Specs.Storage { fmt.Printf(" Storage: %d x %.0f%s %s\n", storage.Count, storage.Size, storage.Unit, storage.Name) } fmt.Printf(" Available in %d regions\n", len(plan.AvailableRegions)) fmt.Println() } ``` -------------------------------- ### Get Team Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/teams.md Retrieves a specific team by its unique ID. Optional query parameters can be provided. ```APIDOC ## Get Team ### Description Retrieves a specific team by its unique ID. Optional query parameters can be provided. ### Method GET ### Endpoint /teams/{teamID} ### Parameters #### Path Parameters - **teamID** (int) - Required - The ID of the team to retrieve #### Query Parameters - **opts** (*GetOptions) - Optional - Query options ### Response #### Success Response (200) - **Team** - Single team object - ** extit{Response}** - Response metadata ### Request Example ```go team, _, err := client.Teams.Get(123, nil) if err != nil { log.Fatal(err) } log.Println("Team:", team.Name) log.Println("Account Credit:", team.Credit.Account.Remaining, team.Credit.Account.Currency) log.Println("Promo Credit:", team.Credit.Promo.Remaining, team.Credit.Promo.Currency) ``` ``` -------------------------------- ### Request New Server Source: https://github.com/cherryservers/cherrygo/blob/master/README.md Create a new server instance by providing project ID, image slug, region slug, and plan slug. The response includes details of the newly created server. ```go addServerRequest := cherrygo.CreateServer{ ProjectID: projectID, Image: imageSlug, Region: regionSlug, Plan: planSlug, } server, _, err := c.Servers.Create(&addServerRequest) if err != nil { log.Fatal("Error while creating new server: ", err) } log.Println(server.ID, server.Name, server.Hostname) ``` -------------------------------- ### Get Server Power State Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/servers.md Retrieves the current power state of a server. The state can be 'on' or 'off'. ```go state, _, err := client.Servers.PowerState(serverID) if err != nil { log.Fatal(err) } log.Println("Power state:", state.Power) ``` -------------------------------- ### Create Server Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/servers.md Orders and creates a new server instance with specified configuration parameters. ```APIDOC ## Create Server ### Description Orders a new server. ### Method POST ### Endpoint /servers ### Parameters #### Request Body - **request** (*CreateServer) - Required - Server creation parameters ##### Request Fields (CreateServer) - **ProjectID** (int) - Required - The project ID for the server - **Plan** (string) - Required - Plan slug (e.g., "baremetal_0") - **Region** (string) - Required - Region slug (e.g., "eu_nord_1") - **Image** (string) - Optional - OS image slug (if not specified, server will be in provisioning state) - **Hostname** (string) - Optional - Server hostname - **SSHKeys** ([]string) - Optional - List of SSH key IDs to add to the server - **IPAddresses** ([]string) - Optional - List of IP address IDs to assign - **UserData** (string) - Optional - Cloud-init user data script - **Tags** (*map[string]string) - Optional - Custom tags - **SpotInstance** (bool) - Optional - Request spot instance pricing (default: false) - **OSPartitionSize** (int) - Optional - OS partition size in GB - **IPXE** (string) - Optional - iPXE boot script URL - **StorageID** (int) - Optional - Block storage ID to attach - **Cycle** (string) - Optional - Billing cycle slug - **DiscountCode** (string) - Optional - Discount code for pricing ### Response #### Success Response (200) - **server** (Server) - Created server object - **resp** (*Response) - Response metadata ### Request Example ```go newServer, _, err := client.Servers.Create(&cherrygo.CreateServer{ ProjectID: projectID, Plan: "baremetal_0", Region: "eu_nord_1", Image: "ubuntu_22_04", Hostname: "web-server-01", SSHKeys: []string{"key1", "key2"}, }) if err != nil { log.Fatal(err) } log.Printf("Created server: %d - %s", newServer.ID, newServer.Name) ``` ``` -------------------------------- ### Integrate SSH Keys with Server Creation Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/ssh-keys.md Shows how to associate SSH keys with a new server during its creation by providing an array of SSH key IDs. ```go server, _, err := client.Servers.Create(&cherrygo.CreateServer{ ProjectID: projectID, Plan: "baremetal_0", Region: "eu_nord_1", Image: "ubuntu_22_04", SSHKeys: []string{"123", "456"}, // SSH key IDs }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Server Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/servers.md Retrieves detailed information for a specific server by its ID. Optional query parameters can be provided. ```APIDOC ## Get Server ### Description Retrieves details for a specific server. ### Method GET ### Endpoint /servers/{serverID} ### Parameters #### Path Parameters - **serverID** (int) - Required - The server ID #### Query Parameters - **opts** (*GetOptions) - Optional - Query options ### Response #### Success Response (200) - **server** (Server) - The Server object. - **resp** (*Response) - Response metadata. ### Request Example ```go server, _, err := client.Servers.Get(serverID, nil) if err != nil { log.Fatal(err) } log.Println("Server:", server.Name) log.Println("Hostname:", server.Hostname) log.Println("Region:", server.Region.Name) log.Println("Plan:", server.Plan.Name) ``` ``` -------------------------------- ### Get Backup Details Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/backups.md Retrieves the details of a specific backup storage, including its size, usage, and other relevant information. ```APIDOC ## Get Backup Details ### Description Retrieves the details of a specific backup storage, including its size, usage, and other relevant information. ### Method GET (Implied by `client.Backups.Get`) ### Endpoint `/backups/{backupID}` (Implied) ### Parameters #### Path Parameters - **backupID** (string) - Required - The ID of the backup storage to retrieve. #### Query Parameters - **options** (object) - Optional - Additional options for retrieving backup details. ``` -------------------------------- ### Minimal Client Initialization Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/configuration.md Initializes the CherryGo client with minimal configuration, relying on the CHERRY_AUTH_TOKEN environment variable for authentication. Error handling is included. ```go client, err := cherrygo.NewClient() if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create Backup Storage and Enable Methods Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/backups.md Creates a new backup storage instance and enables specific backup methods like Borg and SFTP. For SFTP, IP whitelisting can be configured. ```go // Create backup backup, _, err := client.Backups.Create(&cherrygo.CreateBackup{ ServerID: serverID, BackupPlanSlug: "storage_1000", RegionSlug: "eu_nord_1", }) if err != nil { log.Fatal(err) } // Enable Borg for automated backups _, _, err = client.Backups.UpdateBackupMethod(&cherrygo.UpdateBackupMethod{ BackupStorageID: backup.ID, BackupMethodName: "borg", Enabled: true, }) if err != nil { log.Fatal(err) } // Enable SFTP with whitelist _, _, err = client.Backups.UpdateBackupMethod(&cherrygo.UpdateBackupMethod{ BackupStorageID: backup.ID, BackupMethodName: "ftp", Enabled: true, Whitelist: []string{"server-ip-address"}, }) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/users.md Retrieves information about a specific user by their unique ID. This method allows fetching details for any user when their ID is known. ```APIDOC ## Get ### Description Retrieves information about a specific user by ID. ### Method GET ### Endpoint /users/{userID} ### Parameters #### Path Parameters - **userID** (int) - Required - The user ID #### Query Parameters - **opts** (*GetOptions) - Optional - Query options ### Response #### Success Response (200) - **User** (User) - User details - **Response** (*Response) - Response metadata ### Request Example ```go user, _, err := client.Users.Get(456, nil) if err != nil { log.Fatal(err) } log.Printf("User: %s %s", user.FirstName, user.LastName) log.Printf("Email: %s (verified: %v)", user.Email, user.EmailVerified) ``` ``` -------------------------------- ### List Server Cycles Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/servers.md Fetches a list of available server cycles and prints their names and slugs. Requires the cherrygo client to be initialized. ```go cycles, _, err := client.Servers.ListCycles(nil) if err != nil { log.Fatal(err) } for _, cycle := range cycles { log.Printf("%s (%s)", cycle.Name, cycle.Slug) } ``` -------------------------------- ### Configure CherryGo Client Options Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/INDEX.md Initialize the CherryGo client with custom options such as authentication token, API URL, user agent, or a custom HTTP client. ```go client, err := cherrygo.NewClient( cherrygo.WithAuthToken("token"), cherrygo.WithURL("https://api.example.com/v1/"), cherrygo.WithUserAgent("MyApp/1.0"), cherrygo.WithHTTPClient(customHTTPClient), ) ``` -------------------------------- ### Get IP Address Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/ip-addresses.md Retrieves details of a specific IP address using its unique ID. Optional query parameters can be provided. ```APIDOC ## Get IP Address ### Description Retrieves a specific IP address by ID. Supports optional query parameters. ### Method GET ### Endpoint /ips/{ipID} ### Parameters #### Path Parameters - **ipID** (string) - Yes - The IP address ID #### Query Parameters - **opts** (*GetOptions) - No - Query options ### Response #### Success Response (200) - **IPAddress** - IP address details - **Response** - Response metadata ### Response Example ```json { "ID": "ip-123", "Address": "192.168.1.1", "Cidr": "192.168.1.0/24", "Type": "ipv4", "Region": { "Name": "eu_nord_1" }, "PtrRecord": "server.example.com", "ARecord": "server.example.com", "AssignedTo": { "ID": "server-1", "Name": "web-server-1" }, "Tags": { "environment": "production" } } ``` ``` -------------------------------- ### Initialize Client with Environment Variable Source: https://github.com/cherryservers/cherrygo/blob/master/README.md Create a new Cherrygo client instance. It will automatically use the CHERRY_AUTH_TOKEN environment variable if set. ```go func main() { c, err := cherrygo.NewClient() } ``` -------------------------------- ### Get SSH Key Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/ssh-keys.md Retrieves the details of a specific SSH key using its unique identifier. Optional query parameters can be provided. ```APIDOC ## Get SSH Key ### Description Retrieves a specific SSH key by ID. ### Method GET (Assumed based on common REST patterns for retrieving a specific resource) ### Endpoint /ssh-keys/{sshKeyID} ### Parameters #### Path Parameters - **sshKeyID** (int) - Required - The unique identifier of the SSH key. #### Query Parameters - **opts** (*GetOptions) - Optional - Query options. ### Response #### Success Response (200) - **SSHKey** - An object containing the SSH key details. - ***Response** - Response metadata. #### Response Example ```json { "id": 123, "label": "My Server Key", "fingerprint": "SHA256:...", "created": "2023-01-01T12:00:00Z" } ``` ``` -------------------------------- ### List Available Server Plans Source: https://github.com/cherryservers/cherrygo/blob/master/README.md Retrieve a list of available server plans for a given team. This is useful for understanding available configurations. ```go plans, _, err := c.Plans.List(teamID, nil) if err != nil { log.Fatalf("Plans error: %v", err) } for _, p := range plans { log.Println(p.Name, p.Slug) } ``` -------------------------------- ### Initialize Client with Direct Token Source: https://github.com/cherryservers/cherrygo/blob/master/README.md Create a new Cherrygo client instance and pass the API token directly using WithAuthToken option. ```go func main() { c, err := cherrygo.NewClient(cherrygo.WithAuthToken("your-api-token")) } ``` -------------------------------- ### Client Initialization with Custom Timeouts Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/configuration.md Initializes the CherryGo client with a custom HTTP client that has a specified timeout. Error handling is included. ```go customHTTPClient := &http.Client{ Timeout: time.Duration(60 * time.Second), } client, err := cherrygo.NewClient( cherrygo.WithAuthToken("token"), cherrygo.WithHTTPClient(customHTTPClient), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### CreateServer Struct Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/types.md Defines the parameters for creating a new server instance, including project ID, plan, hostname, image, region, SSH keys, IP addresses, user data, and storage details. ```go type CreateServer struct { ProjectID int Plan string Hostname string Image string Region string SSHKeys []string IPAddresses []string UserData string Tags *map[string]string SpotInstance bool OSPartitionSize int IPXE string StorageID int Cycle string DiscountCode string } ``` -------------------------------- ### List OS Images for a Plan Source: https://github.com/cherryservers/cherrygo/blob/master/README.md Retrieve a list of available operating system images for a specific server plan. Requires the plan's slug. ```go images, _, err := c.Images.List(planSlug, nil) if err != nil { log.Fatal("Error", err) } for _, i := range images { log.Println(i.Name, i.Slug) } ``` -------------------------------- ### Initialize Client and Handle API Call Errors Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/configuration.md Demonstrates basic error handling for both client initialization and subsequent API calls. Catches network, parsing, and API-specific errors. ```go client, err := cherrygo.NewClient() if err != nil { // Error during initialization (missing token, invalid URL, etc.) log.Fatal(err) } teams, _, err := client.Teams.List(nil) if err != nil { // Error during API call (network error, API error, parsing error) log.Fatal(err) } ``` -------------------------------- ### Get Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/backups.md Retrieves a specific backup storage by ID. This method fetches the details of a particular backup storage instance using its unique identifier. ```APIDOC ## Get ### Description Retrieves a specific backup storage by ID. ### Method GET ### Endpoint /backups/{backupID} ### Parameters #### Path Parameters - **backupID** (int) - Yes - The backup storage ID #### Query Parameters - **opts** (*GetOptions) - No - Query options ### Response #### Success Response (200) - **BackupStorage** - Backup storage details - **Response** - Response metadata ### Example ```go backup, _, err := client.Backups.Get(123, nil) if err != nil { log.Fatal(err) } log.Printf("Attached to: %s\n", backup.AttachedTo.Hostname) log.Printf("Size: %d GB\n", backup.SizeGigabytes) log.Printf("Used: %d GB\n", backup.UsedGigabytes) log.Println("Backup Methods:") for _, method := range backup.Methods { status := "disabled" if method.Enabled { status = "enabled" } log.Printf(" - %s (%s)", method.Name, status) } ``` ``` -------------------------------- ### Get SSH Key by ID Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/ssh-keys.md Fetches details for a specific SSH key using its unique identifier. Optional query parameters can be provided. ```go key, _, err := client.SSHKeys.Get(123, nil) if err != nil { log.Fatal(err) } log.Printf("Key: %s\n", key.Label) log.Printf("Fingerprint: %s\n", key.Fingerprint) log.Printf("Created: %s\n", key.Created) ``` -------------------------------- ### List Server Plans Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/QUICKSTART.md Retrieve a list of available server plans for a given team. The slug of the first plan is extracted. ```go plans, _, err := client.Plans.List(teamID, nil) if err != nil { log.Fatal(err) } // Find a plan planSlug := plans[0].Slug log.Printf("Available plan: %s", plans[0].Name) ``` -------------------------------- ### Initialize Cherry Servers Go Client Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/QUICKSTART.md Initialize the Cherry Servers Go client. It can be initialized using an environment variable or an explicit API token. ```go package main import ( "log" "github.com/cherryservers/cherrygo/v3" ) func main() { // Initialize with environment variable CHERRY_AUTH_TOKEN client, err := cherrygo.NewClient() if err != nil { log.Fatal(err) } // Or use explicit token // client, err := cherrygo.NewClient( // cherrygo.WithAuthToken("your-api-token"), // ) } ``` -------------------------------- ### Get Specific Storage Volume Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/storage.md Retrieves the details of a specific block storage volume using its unique ID. Optional query parameters can be provided. ```APIDOC ## Get Specific Storage Volume ### Description Retrieves a specific storage volume by ID. ### Method GET ### Endpoint /storage/{storageID} ### Parameters #### Path Parameters - **storageID** (int) - Required - The storage volume ID #### Query Parameters - **opts** (*GetOptions) - Optional - Query options ### Response #### Success Response (200) - **BlockStorage** - Storage volume details - **Response** - Response metadata ### Example ```go storage, _, err := client.Storages.Get(789, nil) if err != nil { log.Fatal(err) } log.Printf("Volume: %s\n", storage.Name) log.Printf("Size: %d %s\n", storage.Size, storage.Unit) log.Printf("Used: %d %s\n", storage.UsedGigabytes, "GB") log.Printf("VLAN ID: %s\n", storage.VlanID) log.Printf("Discovery IP: %s\n", storage.DiscoveryIP) ``` ``` -------------------------------- ### CreateProject Struct Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/types.md Represents the data required to create a new project, including its name and whether BGP is enabled. ```go type CreateProject struct { Name string Bgp bool } ``` -------------------------------- ### Get Specific Region Details Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/api-reference/regions.md Fetches detailed information for a single, specified region using its slug. Useful for checking region-specific configurations or availability. ```go region, _, err := client.Regions.Get("eu_nord_1", nil) if err != nil { log.Fatal(err) } log.Printf("Region: %s\n", region.Name) log.Printf("Location: %s\n", region.Location) log.Printf("ISO2: %s\n", region.RegionIso2) log.Printf("BGP ASN: %d\n", region.BGP.Asn) ``` -------------------------------- ### Accessing Services via Client Instance Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/INDEX.md Services are accessed through a shared Client instance. This shows how to access different service clients like Teams, Projects, and Servers. ```go client.Teams // TeamsService client.Projects // ProjectsService client.Servers // ServersService client.Plans // PlansService client.Images // ImagesService client.Regions // RegionsService client.IPAddresses // IpAddressesService client.SSHKeys // SSHKeysService client.Storages // StoragesService client.Backups // BackupsService client.Users // UsersService ``` -------------------------------- ### Manage Server Lifecycle Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/QUICKSTART.md Perform common server management operations including power on, status check, reboot, power off, and deletion. ```go // Power on client.Servers.PowerOn(server.ID) // Get status server, _, err := client.Servers.Get(server.ID, nil) log.Printf("State: %s, Status: %s", server.State, server.Status) // Reboot client.Servers.Reboot(server.ID) // Power off client.Servers.PowerOff(server.ID) // Delete client.Servers.Delete(server.ID) ``` -------------------------------- ### Handling Unauthorized (401) Errors Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/errors.md Provides an example of how to detect and respond to 'Unauthorized' errors (HTTP 401), typically indicating issues with authentication credentials. ```Go teams, _, err := client.Teams.List(nil) if err != nil { if strings.Contains(err.Error(), "Unauthorized") { log.Println("Authentication failed - check API token") } } ``` -------------------------------- ### List Servers in a Project Source: https://github.com/cherryservers/cherrygo/blob/master/_autodocs/QUICKSTART.md Retrieve a list of all servers within a specified project. The output includes the server ID, hostname, and its current state. ```go servers, _, err := client.Servers.List(projectID, nil) for _, server := range servers { log.Printf("%d: %s (state: %s)", server.ID, server.Hostname, server.State) } ```