### Install golangci-lint Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/CONTRIBUTING.md Use this command to install the golangci-lint tool, which is used for linting the code. ```bash make setup ``` -------------------------------- ### Example Code Snippet Structure Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/INDEX.md Illustrates the standard format for code examples in the documentation, including imports, method calls, result usage, and error handling. ```go import ( "context" "go.mongodb.org/ops-manager/opsmngr" ) // Create/setup org, resp, err := client.Organizations.Get(context.Background(), orgID) // Handle error if err != nil { log.Fatal(err) } // Use result fmt.Println(org.Name) ``` -------------------------------- ### Install Git Pre-commit Hook Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/CONTRIBUTING.md Install the git pre-commit hook to automatically format and check code before committing. ```bash make link-git-hooks ``` -------------------------------- ### Create User with Roles (Go) Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/users.md Example of creating a new user with initial organization-level roles using the Go client. Ensure the 'opsmngr' package is imported and a client is initialized. ```go // Create user with initial roles newUser := &opsmngr.User{ Username: "admin@example.com", Password: "SecurePassword123!", FirstName: "Admin", LastName: "User", EmailAddress: "admin@example.com", Roles: []*opsmngr.UserRole{ { RoleName: "ORG_OWNER", OrgID: orgID, }, }, } user, _, err := client.Users.Create(context.Background(), newUser) ``` -------------------------------- ### Import Ops Manager Client Package Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/README.md Import the necessary package to start using the Ops Manager client. ```go import "go.mongodb.org/ops-manager/opsmngr" ``` -------------------------------- ### Initialize Client for Cloud Manager (Default) Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Creates a client for Cloud Manager with minimal configuration, including authentication setup using digest transport. ```go import ( "github.com/mongodb-forks/digest" "go.mongodb.org/ops-manager/opsmngr" ) // Setup authentication t := digest.NewTransport("public_key", "private_key") tc, _ := t.Client() // Create client with minimal configuration client, _ := opsmngr.New(tc) ``` -------------------------------- ### Construct New Ops Manager Client Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/README.md Create a new Ops Manager client instance. If no context is available, use context.Background() as a starting point. ```go client := opsmngr.NewClient(nil) ``` -------------------------------- ### Get Project Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Retrieves a single project by its ID. ```APIDOC ## Get Project ### Description Retrieves a single project by ID. ### Method GET ### Endpoint /api/public/v1.0/groups/{groupID} ### Parameters #### Path Parameters - **groupID** (string) - Required - Project ID ### Response #### Success Response (200) - **Project** (Project) - The retrieved project object. ### Request Example ```go project, resp, err := client.Projects.Get(context.Background(), "507f1f77bcf86cd799439011") if err != nil { log.Fatal(err) } fmt.Printf("Project: %s\n", project.Name) ``` ``` -------------------------------- ### Handling ArgError Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/errors.md Example demonstrating how to catch and process an ArgError, typically occurring with invalid method arguments. ```go // This will return ArgError org, _, err := client.Organizations.Get(ctx, "") if err != nil { fmt.Println(err.Error()) // "orgID is invalid because must be set" if argErr, ok := err.(*opsmngr.ArgError); ok { fmt.Println("Argument validation failed") } } ``` -------------------------------- ### Get Project By Name Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Retrieves a single project by its name. ```APIDOC ## Get Project By Name ### Description Retrieves a single project by name. ### Method GET ### Endpoint /api/public/v1.0/groups?name={groupName} ### Parameters #### Query Parameters - **groupName** (string) - Required - Project name ### Response #### Success Response (200) - **Project** (Project) - The retrieved project object. ### Request Example ```go project, resp, err := client.Projects.GetByName(context.Background(), "MyProject") if err != nil { log.Fatal(err) } fmt.Printf("Project ID: %s\n", project.ID) ``` ``` -------------------------------- ### Get Project by Name Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Retrieve details for a specific project using its name. Project names must be unique within an organization. ```go // Get project by name project, _, err := client.Projects.GetByName(ctx, "ProjectName") ``` -------------------------------- ### Get Project by ID Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Retrieves a single project by its unique ID. Ensure the provided groupID is not empty. ```go project, resp, err := client.Projects.Get(context.Background(), "507f1f77bcf86cd799439011") if err != nil { log.Fatal(err) } fmt.Printf("Project: %s\n", project.Name) ``` -------------------------------- ### Handling API ErrorResponse Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/errors.md Example of how to check for and extract details from an ErrorResponse when an API call fails. ```go org, _, err := client.Organizations.Get(ctx, "invalid-id") if err != nil { if errResp, ok := err.(*opsmngr.ErrorResponse); ok { fmt.Printf("API Error: %s (%s)\n", errResp.Reason, errResp.ErrorCode) fmt.Printf("Status: %d\n", errResp.HTTPCode) fmt.Printf("Detail: %s\n", errResp.Detail) } else { fmt.Printf("Other error: %v\n", err) } } ``` -------------------------------- ### Authenticate and Initialize Ops Manager Client Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/README.md Initialize an authenticated Ops Manager client using digest access authentication. This example demonstrates setting a custom base URL for Ops Manager. Ensure your public and private keys are correctly provided. ```go import ( "context" "log" "github.com/mongodb-forks/digest" "go.mongodb.org/ops-manager/opsmngr" ) func main() { t := digest.NewTransport("your public key", "your private key") tc, err := t.Client() if err != nil { log.Fatalf(err.Error()) } // Note: If no Base URL is set the client is set to work with Cloud Manager by default clientops := opsmngr.SetBaseURL("https://opsmanagerurl/" + opsmngr.APIPublicV1Path) client, err := opsmngr.New(tc, clientops) if err != nil { log.Fatalf(err.Error()) } orgs, _, err := client.Organizations.List(context.Background(), nil) } ``` -------------------------------- ### Get Project by ID Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Retrieve details for a specific project using its unique ID. Ensure the projectID is correct. ```go // Get project by ID project, _, err := client.Projects.Get(ctx, projectID) ``` -------------------------------- ### Get User by Name Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/users.md Retrieves a user using their username or email address. Throws an error if the username is empty. ```go user, resp, err := client.Users.GetByName(context.Background(), "user@example.com") if err != nil { log.Fatal(err) } fmt.Printf("User ID: %s\n", user.ID) ``` -------------------------------- ### Client Authentication Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/client.md The ops-manager library requires an authenticated http.Client to be passed during client creation. This example demonstrates using the digest package for authentication. ```APIDOC ## Authentication The ops-manager library does not directly handle authentication. Instead, pass an authenticated `http.Client` when creating a client: ```go import "github.com/mongodb-forks/digest" t := digest.NewTransport("public_api_key", "private_api_key") tc, err := t.Client() if err != nil { log.Fatal(err) } client, err := opsmngr.New(tc, opsmngr.SetBaseURL("https://opsmanager.example.com/api/public/v1.0/"), ) ``` All requests made by an authenticated client include the API credentials, so do not share instances between different users. ``` -------------------------------- ### Handling Context Cancellation Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/errors.md Example of detecting and handling a context cancellation error, which occurs when a request's context is explicitly cancelled. ```go ctx, cancel := context.WithCancel(context.Background()) cancel() org, _, err := client.Organizations.Get(ctx, orgID) if err == context.Canceled { fmt.Println("Request was cancelled") } ``` -------------------------------- ### Handling HTTP Status Errors (Conflict) Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/errors.md Example of detecting a 409 Conflict HTTP error using errors.As with an ErrorResponse, useful for preventing duplicate resource creation. ```go // Attempt to create duplicate project project := &opsmngr.Project{Name: "ExistingProject"} _, _, err := client.Projects.Create(ctx, project, nil) if err != nil { errResp := &opsmngr.ErrorResponse{} if errors.As(err, &errResp) { if errResp.HTTPCode == 409 { fmt.Println("Project already exists") } } } ``` -------------------------------- ### Initialize Client for Ops Manager with Full Options Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Creates a client for Ops Manager with all available configuration options set, including base URL, user agent, and raw response capture. ```go import ( "github.com/mongodb-forks/digest" "go.mongodb.org/ops-manager/opsmngr" ) // Setup authentication t := digest.NewTransport("public_key", "private_key") tc, _ := t.Client() // Create client with full configuration client, err := opsmngr.New(tc, opsmngr.SetBaseURL("https://opsmanager.example.com/api/public/v1.0/"), opsmngr.SetUserAgent("ops-cli/3.0.0"), opsmngr.SetWithRaw(), ) ``` -------------------------------- ### Client Initialization with Digest Authentication Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/client.md Demonstrates how to create an authenticated HTTP client using digest authentication and then initialize the Ops Manager client with it. ```go import "github.com/mongodb-forks/digest" t := digest.NewTransport("public_api_key", "private_api_key") tc, err := t.Client() if err != nil { log.Fatal(err) } client, err := opsmngr.New(tc, opsmngr.SetBaseURL("https://opsmanager.example.com/api/public/v1.0/"), ) ``` -------------------------------- ### Initialize Client for Development/Testing Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Configures a client for local development or testing, using a local HTTP client and a custom base URL for a development server. ```go import ( "net/http" "go.mongodb.org/ops-manager/opsmngr" ) // Local development server client, _ := opsmngr.New(&http.Client{}, opsmngr.SetBaseURL("http://localhost:8080/api/public/v1.0/"), opsmngr.SetUserAgent("local-dev"), opsmngr.SetWithRaw(), ) ``` -------------------------------- ### Initialize Client with Custom TLS Configuration Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Set up a custom TLS configuration for the HTTP client. Use `InsecureSkipVerify` with caution, as it is not recommended for production environments. ```go import ( "crypto/tls" "net/http" ) tlsConfig := &tls.Config{ InsecureSkipVerify: true, // NOT recommended for production } httpClient := &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, } client, _ := opsmngr.New(httpClient) ``` -------------------------------- ### Initialize Client with Proxy Configuration Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Configure the HTTP client to use a proxy server for requests. Ensure the proxy URL is correctly formatted. ```go import ( "net/http" "net/url" ) proxyURL, _ := url.Parse("http://proxy.example.com:8080") httpClient := &http.Client{ Transport: &http.Transport{ Proxy: http.ProxyURL(proxyURL), }, } client, _ := opsmngr.New(httpClient) ``` -------------------------------- ### Get Organization Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/README.md Retrieves details for a specific organization by its ID. ```APIDOC ## Get Organization ### Description Retrieves details for a specific organization by its ID. ### Method `client.Organizations.Get()` ### Endpoint Not directly specified, but implied to be an API endpoint for retrieving a single organization. ### Parameters #### Path Parameters - **orgID** (string) - Required - The ID of the organization to retrieve. #### Query Parameters None #### Request Body None ### Request Example ```go org, resp, err := client.Organizations.Get(context.Background(), orgID) ``` ### Response #### Success Response - **org** (*opsmngr.Organization) - The organization details. - **resp** (*opsmngr.Response) - HTTP response metadata. #### Response Example ```json { "Name": "Organization Name", "ID": "org_id_123" } ``` ### Error Handling - **err** (`error`) - An error if the request fails. Can be checked for `opsmngr.ErrorResponse`. ``` -------------------------------- ### Get Alert Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/alerts.md Retrieves a specific alert by its ID for a given project. ```APIDOC ## Get Alert ### Description Retrieves a specific alert by ID. ### Method GET ### Endpoint /api/public/v1.0/groups/{projectID}/alerts/{alertID} ### Parameters #### Path Parameters - **projectID** (string) - Yes - Project ID - **alertID** (string) - Yes - Alert ID ### Request Example ```go alert, resp, err := client.Alerts.Get(context.Background(), projectID, alertID) if err != nil { log.Fatal(err) } fmt.Printf("Alert Status: %s\n", alert.Status) ``` ### Response #### Success Response (200) - **AlertId** (string) - The unique identifier for the alert. - **GroupId** (string) - The ID of the project the alert belongs to. - **EventTypeName** (string) - The type of event that triggered the alert. - **Status** (string) - The current status of the alert (e.g., "OPEN", "ACKNOWLEDGED"). - **CreatedAt** (string) - The timestamp when the alert was created. - **UpdatedAt** (string) - The timestamp when the alert was last updated. - **AcknowledgedUntil** (string) - The timestamp until which the alert is acknowledged (if applicable). - **AcknowledgedBy** (string) - The user who acknowledged the alert (if applicable). - **AcknowledgementComment** (string) - The comment provided during acknowledgment (if applicable). #### Response Example ```json { "AlertId": "653b7a4c1234567890abcdef", "GroupId": "653b7a4c1234567890abcdee", "EventTypeName": "MONGODB_REPLICA_SET_PRIMARY_STEP_DOWN", "Status": "OPEN", "CreatedAt": "2023-10-27T10:00:00Z", "UpdatedAt": "2023-10-27T10:05:00Z", "AcknowledgedUntil": null, "AcknowledgedBy": null, "AcknowledgementComment": null } ``` ``` -------------------------------- ### Get Team Projects Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/teams.md Retrieves a list of projects that a team has access to. ```APIDOC ## Get Team Projects ### Description Retrieves a list of projects that a team has access to. ### Method GET ### Endpoint /api/public/v1.0/orgs/{orgID}/teams/{teamID}/projects ### Parameters #### Path Parameters - **orgID** (string) - Yes - Organization ID - **teamID** (string) - Yes - Team ID ### Request Example ```go projects, resp, err := client.Teams.GetTeamProjects(context.Background(), orgID, teamID) if err != nil { log.Fatal(err) } for _, project := range projects { fmt.Printf("Project: %s (ID: %s)\n", project.Name, project.ID) } ``` ### Response #### Success Response (200) - **Projects** ([]*Project) - A list of projects the team has access to. ``` -------------------------------- ### Get Team Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/teams.md Retrieves a specific team by its ID within an organization. ```APIDOC ## Get Team ### Description Retrieves a specific team by ID. ### Method GET ### Endpoint /api/public/v1.0/orgs/{orgID}/teams/{teamID} ### Parameters #### Path Parameters - **orgID** (string) - Yes - Organization ID - **teamID** (string) - Yes - Team ID ### Request Example ```go team, resp, err := client.Teams.Get(context.Background(), orgID, teamID) if err != nil { log.Fatal(err) } fmt.Printf("Team: %s\n", team.Name) ``` ### Response #### Success Response (200) - **ID** (string) - The unique identifier for the team. - **Name** (string) - The name of the team. - **UserIDs** ([]string) - A list of user IDs that are members of the team. ``` -------------------------------- ### Get Project Teams Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Retrieves all teams currently assigned to a project. Supports pagination. ```APIDOC ## Get Teams ### Description Retrieves all teams in a project. ### Method GET ### Endpoint /projects/{projectID}/teams ### Parameters #### Path Parameters - **projectID** (string) - Yes - Project ID #### Query Parameters - **PageNum** (int) - No - Page number for pagination - **ItemsPerPage** (int) - No - Number of items per page ### Response #### Success Response (200) - **TeamsAssigned** (*TeamsAssigned) - Object containing assigned teams - **Results** ([]*Team) - List of teams assigned to the project - **TeamID** (string) - The ID of the team ### Request Example ```go teams, resp, err := client.Projects.GetTeams(context.Background(), projectID, &opsmngr.ListOptions{ PageNum: 1, ItemsPerPage: 100, }) if err != nil { log.Fatal(err) } for _, team := range teams.Results { fmt.Printf("Team: %s\n", team.TeamID) } ``` ``` -------------------------------- ### Create User Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Create a new user with specified credentials and personal information. Ensure a strong password is used. ```go // Create user user, _, err := client.Users.Create(ctx, &opsmngr.User{ Username: "newuser@example.com", Password: "SecurePassword123!", FirstName: "John", LastName: "Doe", }) ``` -------------------------------- ### Create Project Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Create a new project with a specified name. This operation may require additional options. ```go // Create project project, _, err := client.Projects.Create(ctx, &opsmngr.Project{ Name: "NewProject", }, nil) ``` -------------------------------- ### Initialize Client with Digest Authentication Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Use digest authentication for secure client initialization. Ensure you have your public and private keys. ```go import ( "github.com/mongodb-forks/digest" "go.mongodb.org/ops-manager/opsmngr" ) t := digest.NewTransport("public_key", "private_key") tc, err := t.Client() if err != nil { log.Fatal(err) } client, _ := opsmngr.New(tc) ``` -------------------------------- ### Configure Client using Environment Variables Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Read client configuration, such as API keys and base URL, from environment variables. This promotes secure credential management. ```go import ( "os" "github.com/mongodb-forks/digest" "go.mongodb.org/ops-manager/opsmngr" ) // Read configuration from environment publicKey := os.Getenv("OPS_MANAGER_PUBLIC_KEY") privateKey := os.Getenv("OPS_MANAGER_PRIVATE_KEY") baseURL := os.Getenv("OPS_MANAGER_URL") if baseURL == "" { baseURL = "https://cloud.mongodb.com/" } // Create authenticated client t := digest.NewTransport(publicKey, privateKey) tc, err := t.Client() if err != nil { log.Fatal(err) } // Create client with environment configuration client, err := opsmngr.New(tc, opsmngr.SetBaseURL(baseURL), opsmngr.SetUserAgent("env-configured-client"), ) ``` -------------------------------- ### Alerts Operations Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Reference for common operations related to alerts, including listing, getting, and acknowledging alerts. ```APIDOC ## Alerts Operations ### List Alerts - **Description**: Lists alerts for a given project, with options for filtering and pagination. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `projectID` (string) - Required - The ID of the project. - `options` (*opsmngr.AlertsListOptions) - Optional - Options for filtering (e.g., status) and pagination. ### Get Specific Alert - **Description**: Retrieves details of a specific alert by its ID for a given project. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `projectID` (string) - Required - The ID of the project. - `alertID` (string) - Required - The ID of the alert. ### Acknowledge Alert - **Description**: Acknowledges a specific alert, optionally setting an expiration time and comment. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `projectID` (string) - Required - The ID of the project. - `alertID` (string) - Required - The ID of the alert to acknowledge. - `request` (*opsmngr.AcknowledgeRequest) - Required - The acknowledgement details, including comment and expiration. ``` -------------------------------- ### Users Operations Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Reference for common operations related to users, including getting, creating, and deleting users. ```APIDOC ## Users Operations ### Get User by ID - **Description**: Retrieves a user by their ID. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `userID` (string) - Required - The ID of the user. ### Get User by Username - **Description**: Retrieves a user by their username (email address). - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `username` (string) - Required - The username of the user. ### Create User - **Description**: Creates a new user. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `user` (*opsmngr.User) - Required - The user object with details like username, password, first name, and last name. ### Delete User - **Description**: Deletes a user by their ID. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `userID` (string) - Required - The ID of the user to delete. ``` -------------------------------- ### Handle Client Creation Errors Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Always check for errors when creating a client instance, especially when providing custom configurations like a base URL. ```go client, err := opsmngr.New(httpClient, opsmngr.SetBaseURL("invalid url"), ) if err != nil { log.Fatalf("Failed to create client: %v", err) } ``` -------------------------------- ### Get User by Name Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/users.md Retrieves a user by their username or email address. Requires a valid context and username. ```APIDOC ## Get User by Name ### Description Retrieves a user by username or email address. ### Method GET (Implied by SDK method) ### Endpoint /api/public/v1.0/users?username={username} ### Parameters #### Query Parameters - **username** (string) - Required - Username or email address #### Request Example ```go user, resp, err := client.Users.GetByName(context.Background(), "user@example.com") if err != nil { log.Fatal(err) } fmt.Printf("User ID: %s\n", user.ID) ``` ### Response #### Success Response (200) - **User** (*User) - The retrieved user object. - **Response** (*Response) - The API response object. #### Response Example ```json { "id": "507f1f77bcf86cd799439011", "username": "user@example.com", "firstName": "Test", "lastName": "User" } ``` ``` -------------------------------- ### List Organization Users (Go) Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/users.md Demonstrates how to list all users within a specific organization using the Go client. Requires an initialized client and the organization ID. ```go // Use Organizations service to list users in an org users, _, err := client.Organizations.ListUsers(ctx, orgID, &opsmngr.ListOptions{ PageNum: 1, ItemsPerPage: 100, }) if err != nil { log.Fatal(err) } for _, user := range users.Results { fmt.Printf("User: %s (%s)\n", user.Username, user.EmailAddress) } ``` -------------------------------- ### Get User by ID Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/users.md Retrieves a user by their unique ID. Requires a valid context and user ID. ```APIDOC ## Get User by ID ### Description Retrieves a user by ID. ### Method GET (Implied by SDK method) ### Endpoint /api/public/v1.0/users/{userID} ### Parameters #### Path Parameters - **userID** (string) - Required - User ID (24-hex string) #### Request Example ```go user, resp, err := client.Users.Get(context.Background(), "507f1f77bcf86cd799439011") if err != nil { log.Fatal(err) } fmt.Printf("User: %s (%s %s) ", user.Username, user.FirstName, user.LastName) ``` ### Response #### Success Response (200) - **User** (*User) - The retrieved user object. - **Response** (*Response) - The API response object. #### Response Example ```json { "id": "507f1f77bcf86cd799439011", "username": "testuser", "firstName": "Test", "lastName": "User" } ``` ``` -------------------------------- ### Minimal Client Creation Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Create a minimal client for interacting with the Ops Manager API. Ensure you have your public and private keys. ```go import ( "github.com/mongodb-forks/digest" "go.mongodb.org/ops-manager/opsmngr" ) t := digest.NewTransport("public_key", "private_key") tc, _ := t.Client() client, _ := opsmngr.New(tc) ``` -------------------------------- ### Get Teams Assigned to a Project Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Retrieves all teams currently assigned to a project. Supports pagination via ListOptions. ```go teams, resp, err := client.Projects.GetTeams(context.Background(), projectID, &opsmngr.ListOptions{ PageNum: 1, ItemsPerPage: 100, }) if err != nil { log.Fatal(err) } for _, team := range teams.Results { fmt.Printf("Team: %s\n", team.TeamID) } ``` -------------------------------- ### List Project Users (Go) Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/users.md Shows how to retrieve a list of users belonging to a specific project using the Go client. Requires an initialized client and the project ID. ```go // Use Projects service to list users in a project users, _, err := client.Projects.ListUsers(ctx, projectID, &opsmngr.ListOptions{ PageNum: 1, ItemsPerPage: 100, }) if err != nil { log.Fatal(err) } for _, user := range users { fmt.Printf("User: %s\n", user.Username) } ``` -------------------------------- ### Get Organization by ID Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/organizations.md Retrieves a single organization using its unique ID. The `orgID` parameter must not be empty. ```go org, resp, err := client.Organizations.Get(context.Background(), "507f1f77bcf86cd799439011") if err != nil { log.Fatal(err) } fmt.Printf("Organization: %s\n", org.Name) ``` -------------------------------- ### Get User by ID Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Retrieve details for a specific user using their unique ID. Ensure the userID is correct. ```go // Get user by ID user, _, err := client.Users.Get(ctx, userID) ``` -------------------------------- ### Import Go Client Library Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/README.md Import the Ops Manager client library for Go. You can use the default import path or an alias for brevity. ```go import "go.mongodb.org/ops-manager/opsmngr" ``` ```go import om "go.mongodb.org/ops-manager/opsmngr" // Then: om.NewClient(...), om.Organizations, etc. ``` -------------------------------- ### Use MongoDB Ops Manager Services Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/README.md Demonstrates how to use various services like Organizations and Projects to list and retrieve data. Requires a pre-configured client. ```go // List organizations orgs, resp, err := client.Organizations.List(context.Background(), nil) if err != nil { log.Fatal(err) } for _, org := range orgs.Results { fmt.Printf("Organization: %s\n", org.Name) } // Get a specific organization org, resp, err := client.Organizations.Get(context.Background(), orgID) // List projects projects, resp, err := client.Projects.List(context.Background(), nil) // Get users in a project users, resp, err := client.Projects.ListUsers(context.Background(), projectID, nil) ``` -------------------------------- ### Get Specific Organization Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Retrieve details for a specific organization using its unique ID. Ensure the orgID is correct. ```go // Get specific organization org, _, err := client.Organizations.Get(ctx, orgID) ``` -------------------------------- ### List All Projects Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Retrieves all projects for the authenticated user. Use pagination options to control the number of results returned. ```go projects, resp, err := client.Projects.List(context.Background(), &opsmngr.ListOptions{ PageNum: 1, ItemsPerPage: 100, IncludeCount: true, }) if err != nil { log.Fatal(err) } for _, proj := range projects.Results { fmt.Printf("Project: %s (ID: %s)\n", proj.Name, proj.ID) } ``` -------------------------------- ### Create New Project Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Creates a new project with the specified details. The 'Name' field is required in the project details. The owner ID can be specified via options. ```go newProject := &opsmngr.Project{ Name: "NewProject", } project, resp, err := client.Projects.Create(context.Background(), newProject, nil) if err != nil { log.Fatal(err) } fmt.Printf("Created project: %s (ID: %s)\n", project.Name, project.ID) ``` -------------------------------- ### Reuse Client Instance Best Practice Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Create a single client instance and reuse it throughout your application for efficiency. The client is thread-safe. ```go import "context" // ✓ Create once, reuse multiple times client, _ := opsmngr.New(httpClient) // Thread-safe to use from multiple goroutines go func() { orgs, _, _ := client.Organizations.List(ctx, nil) }() go func() { projects, _, _ := client.Projects.List(ctx, nil) }() ``` -------------------------------- ### Get User by ID Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/users.md Retrieves a specific user by their unique ID. Ensure the provided userID is a 24-hex string. ```go user, resp, err := client.Users.Get(context.Background(), "507f1f77bcf86cd799439011") if err != nil { log.Fatal(err) } fmt.Printf("User: %s (%s %s)\n", user.Username, user.FirstName, user.LastName) ``` -------------------------------- ### Create New Client with Options Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/client.md Returns a new Ops Manager API client instance with specified options applied, such as base URL and user agent. This method requires an HTTP client that handles authentication. ```go import ( "context" "go.mongodb.org/ops-manager/opsmngr" "github.com/mongodb-forks/digest" "log" ) t := digest.NewTransport("public_key", "private_key") tc, err := t.Client() if err != nil { log.Fatal(err) } // Create client with custom options client, err := opsmngr.New(tc, opsmngr.SetBaseURL("https://opsmanager.example.com/api/public/v1.0/"), opsmngr.SetUserAgent("my-app/1.0"), ) if err != nil { log.Fatal(err) } // Use the client orgs, _, err := client.Organizations.List(context.Background(), nil) ``` -------------------------------- ### Create New Project Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/README.md Creates a new project with a specified name. The project ID is returned upon successful creation. ```go // Create new project newProject := &opsmngr.Project{ Name: "MyProject", } project, _, err := client.Projects.Create(ctx, newProject, nil) if err != nil { log.Fatal(err) } fmt.Printf("Created project with ID: %s\n", project.ID) ``` -------------------------------- ### Get Organization by ID Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/README.md Fetches a specific organization using its unique ID. Ensure the organization ID is valid before calling. ```go // Get specific organization org, _, err := client.Organizations.Get(ctx, "507f1f77bcf86cd799439011") if err != nil { log.Fatal(err) } ``` -------------------------------- ### List All Organizations Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/README.md Retrieves a list of all organizations, optionally including the total count. Use this to get an overview of available organizations. ```go // Get all organizations opts := &opsmngr.OrganizationsListOptions{ ListOptions: opsmngr.ListOptions{ IncludeCount: true, }, } orgs, _, err := client.Organizations.List(ctx, opts) // orgs.Results contains the list // orgs.TotalCount contains total count ``` -------------------------------- ### Combine Multiple Client Options Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Organizes and applies multiple client configuration options using the Options function. Useful for creating reusable option sets. ```go // Create reusable option set opsManagerOpts := opsmngr.Options( opsmngr.SetBaseURL("https://opsmanager.example.com/api/public/v1.0/"), opsmngr.SetUserAgent("my-tool/2.0"), opsmngr.SetWithRaw(), ) // Use the combined options client, err := opsmngr.New(httpClient, opsManagerOpts) ``` -------------------------------- ### Get User by Username Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Retrieve details for a specific user using their username (email address). Usernames must be unique. ```go // Get user by username user, _, err := client.Users.GetByName(ctx, "user@example.com") ``` -------------------------------- ### Run All Unit Tests Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/CONTRIBUTING.md Execute this command in the root of the project directory to run all unit tests. ```bash make test ``` -------------------------------- ### Users Service Interface Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/users.md Defines the interface for the Users service, outlining available operations like Get, Create, and Delete. ```go type UsersService interface { Get(context.Context, string) (*User, *Response, error) GetByName(context.Context, string) (*User, *Response, error) Create(context.Context, *User) (*User, *Response, error) Delete(context.Context, string) (*Response, error) } ``` -------------------------------- ### Create Project Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Creates a new project with the specified details. ```APIDOC ## Create Project ### Description Creates a new project. ### Method POST ### Endpoint /api/public/v1.0/groups ### Parameters #### Request Body - **createRequest** (Project) - Required - Project details (Name required) - **opts** (CreateProjectOptions) - Optional - Project owner ID option ### Response #### Success Response (200) - **Project** (Project) - The newly created project object. ### Request Example ```go newProject := &opsmngr.Project{ Name: "NewProject", } project, resp, err := client.Projects.Create(context.Background(), newProject, nil) if err != nil { log.Fatal(err) } fmt.Printf("Created project: %s (ID: %s)\n", project.Name, project.ID) ``` ``` -------------------------------- ### Invite User to Project Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Invites a user to a project by providing the project ID and invitation details. Returns the created invitation. ```go func (s *ProjectsServiceOp) InviteUser(ctx context.Context, projectID string, invitation *Invitation) (*Invitation, *Response, error) ``` -------------------------------- ### Get Specific Team Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Retrieve details for a specific team within an organization using its ID. Ensure orgID and teamID are correct. ```go // Get specific team team, _, err := client.Teams.Get(ctx, orgID, teamID) ``` -------------------------------- ### List Projects Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Retrieve a list of all projects accessible by the authenticated user. Pagination options can be provided. ```go // List all projects projects, _, err := client.Projects.List(ctx, nil) ``` -------------------------------- ### Initialize Client with Custom HTTP Timeouts Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/configuration.md Configure a custom HTTP client with a specific timeout. This is useful for controlling request duration. ```go import ( "net/http" "time" ) httpClient := &http.Client{ Timeout: 30 * time.Second, } client, _ := opsmngr.New(httpClient, opsmngr.SetBaseURL("https://opsmanager.example.com/api/public/v1.0/"), ) ``` -------------------------------- ### Pagination Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Illustrates how to implement basic pagination for API requests using `ListOptions` to control page number, items per page, and include count. ```APIDOC ## Pagination ### Basic Pagination - **Description**: This example demonstrates how to use `opsmngr.ListOptions` to configure pagination for list operations. It shows setting the page number, the number of items per page, and whether to include the total count in the response. - **Method**: Not applicable (Illustrative code) - **Endpoint**: Not applicable (Illustrative code) - **Parameters**: - `PageNum` (int) - The desired page number (1-based). - `ItemsPerPage` (int) - The number of items to return per page. - `IncludeCount` (bool) - Whether to include the total count of items in the response. ``` -------------------------------- ### Handling Network Errors Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/errors.md Example of using errors.As to check if an error is a net.Error, allowing for specific handling of network-related issues like timeouts. ```go var netErr net.Error org, _, err := client.Organizations.Get(ctx, orgID) if errors.As(err, &netErr) { if netErr.Timeout() { fmt.Println("Request timeout") } else { fmt.Println("Network error:", netErr) } } ``` -------------------------------- ### Get Team Projects Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/teams.md Retrieves a list of all projects that a specific team has access to within an organization. Requires organization ID and team ID. ```go projects, resp, err := client.Teams.GetTeamProjects(context.Background(), orgID, teamID) if err != nil { log.Fatal(err) } for _, project := range projects { fmt.Printf("Project: %s\n", project.Name) } ``` -------------------------------- ### Basic Pagination Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Implement basic pagination for API requests by setting `PageNum`, `ItemsPerPage`, and `IncludeCount` in `ListOptions`. This is useful for retrieving large datasets. ```go opts := &opsmngr.ListOptions{ PageNum: 1, ItemsPerPage: 100, IncludeCount: true, } orgs, _, err := client.Organizations.List(ctx, &opsmngr.OrganizationsListOptions{ ListOptions: *opts, }) ``` -------------------------------- ### Teams Operations Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/QUICK_REFERENCE.md Reference for common operations related to teams, including listing, getting, creating, deleting, and managing users and projects within a team. ```APIDOC ## Teams Operations ### List Organization Teams - **Description**: Lists all teams within a specific organization. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `orgID` (string) - Required - The ID of the organization. - `options` (*opsmngr.ListOptions) - Optional - Options for filtering and pagination. ### Get Specific Team - **Description**: Retrieves details of a specific team by its ID within an organization. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `orgID` (string) - Required - The ID of the organization. - `teamID` (string) - Required - The ID of the team. ### Create Team - **Description**: Creates a new team within an organization. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `orgID` (string) - Required - The ID of the organization. - `team` (*opsmngr.Team) - Required - The team object with details like name and associated user IDs. ### Delete Team - **Description**: Deletes a team by its ID within an organization. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `orgID` (string) - Required - The ID of the organization. - `teamID` (string) - Required - The ID of the team to delete. ### Add Users to Team - **Description**: Adds users to a specific team. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `orgID` (string) - Required - The ID of the organization. - `teamID` (string) - Required - The ID of the team. - `userIDs` ([]string) - Required - A list of user IDs to add to the team. ### Remove User from Team - **Description**: Removes a user from a specific team. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `orgID` (string) - Required - The ID of the organization. - `teamID` (string) - Required - The ID of the team. - `userID` (string) - Required - The ID of the user to remove. ### Get Team Projects - **Description**: Retrieves the projects associated with a specific team. - **Method**: Not applicable (SDK method) - **Endpoint**: Not applicable (SDK method) - **Parameters**: - `ctx` (context.Context) - Required - The context for the request. - `orgID` (string) - Required - The ID of the organization. - `teamID` (string) - Required - The ID of the team. ``` -------------------------------- ### CreateProjectOptions Struct Source: https://github.com/mongodb/go-client-mongodb-ops-manager/blob/master/_autodocs/api-reference/projects.md Specifies options required when creating a new project, notably the project owner's user ID. ```go type CreateProjectOptions struct { ProjectOwnerID string `url:"projectOwnerId,omitempty"` } ```