### Install go-github Source: https://github.com/google/go-github/blob/master/README.md Install the go-github library using the go get command. This command resolves and adds the package and its dependencies to your module. ```bash go get github.com/google/go-github/v88 ``` -------------------------------- ### Install Latest go-github from Master Source: https://github.com/google/go-github/blob/master/README.md To use the top-of-trunk version of the go-github repository, use the '@master' tag with the go get command. ```bash go get github.com/google/go-github/v88@master ``` -------------------------------- ### Manage GPG Keys Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/users.md Provides methods for listing, getting, creating, and deleting GPG keys for a user. The example demonstrates listing GPG keys. ```go // List GPG keys keys, _, err := client.Users.ListGPGKeys(ctx, "") for _, key := range keys { fmt.Printf("GPG Key ID: %s\n", key.GetKeyID()) } ``` -------------------------------- ### Manage SSH Keys Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/users.md Provides methods for listing, getting, creating, editing, and deleting SSH keys for a user. The example shows listing and creating keys. ```go // List SSH keys keys, _, err := client.Users.ListKeys(ctx, "") for _, key := range keys { fmt.Printf("%s: %s\n", key.GetTitle(), key.GetKey()) } // Create SSH key newKey := &github.Key{ Title: github.Ptr("My SSH Key"), Key: github.Ptr("ssh-rsa AAAA..."), } key, _, err := client.Users.CreateKey(ctx, newKey) ``` -------------------------------- ### Accessing Rate Limit Information Source: https://github.com/google/go-github/blob/master/_autodocs/errors.md Example of how to retrieve and print rate limit details from an API response. ```go user, resp, err := client.Users.Get(ctx, "octocat") if err == nil { fmt.Printf("Rate limit: %d/%d remaining\n", resp.Rate.Remaining, resp.Rate.Limit) fmt.Printf("Resets at: %v\n", resp.Rate.Reset.Time) } ``` -------------------------------- ### Create a New Private Repository Source: https://github.com/google/go-github/blob/master/README.md Example of creating a new private repository named 'foo'. Uses helper functions to create pointers for non-repeated fields like Name and Private. ```go // create a new private repository named "foo" repo := &github.Repository{ Name: github.Ptr("foo"), Private: github.Ptr(true), } client.Repositories.Create(ctx, "", repo) ``` -------------------------------- ### Search Repositories Example Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/search.md Searches for repositories based on a query string and specified sorting and ordering options. Use this to find repositories matching specific criteria like language or star count. ```go query := "language:go stars:>1000 sort:stars" result, _, err := client.Search.Repositories(ctx, query, &github.SearchOptions{ Sort: "stars", Order: "desc", ListOptions: github.ListOptions{PerPage: 30}, }) if err != nil { log.Fatal(err) } fmt.Printf("Found %d repositories\n", result.GetTotal()) for _, repo := range result.Repositories { fmt.Printf("%s: %d stars\n", repo.GetFullName(), repo.GetStargazersCount()) } ``` -------------------------------- ### Authenticate as GitHub App Installation with ghinstallation Source: https://github.com/google/go-github/blob/master/README.md Use ghinstallation's Transport to authenticate as a GitHub App installation. This is suitable for most API endpoints that require an access token. ```go import ( "net/http" "github.com/bradleyfalzon/ghinstallation/v2" "github.com/google/go-github/v88/github" ) func main() { // Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99. itr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, "2016-10-19.private-key.pem") // Or for endpoints that require JWT authentication // itr, err := ghinstallation.NewAppsTransportKeyFromFile(http.DefaultTransport, 1, "2016-10-19.private-key.pem") if err != nil { // Handle error. } // Use installation transport with client. client, err := github.NewClient(github.WithTransport(itr)) if err != nil { // Handle error. } // Use client... } ``` -------------------------------- ### Basic GitHub Client Usage Source: https://github.com/google/go-github/blob/master/README.md Construct a new GitHub client and use its services to access the GitHub API. This example shows how to list organizations for a given user. ```go import "github.com/google/go-github/v88/github" import "context" func main() { client, err := github.NewClient() if err != nil { // Handle error. } // list all organizations for user "willnorris" orgs, _, err := client.Organizations.List(context.Background(), "willnorris", nil) } ``` -------------------------------- ### Search Code Example Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/search.md Searches for code across repositories using a query string. Enable TextMatch to include code fragments and line numbers in the results. Useful for finding specific code snippets or functions. ```go query := "function:authenticate language:go repo:google/go-github" result, _, err := client.Search.Code(ctx, query, &github.SearchOptions{ TextMatch: true, }) for _, match := range result.CodeMatches { fmt.Printf("%s:%d\n", match.Path, match.LineNumber) fmt.Printf(" %s\n", match.Fragment) } ``` -------------------------------- ### Create Client with External Rate Limiting Source: https://github.com/google/go-github/blob/master/_autodocs/configuration.md Integrate an external rate limiter with the GitHub client. This example uses `go-github-ratelimit` and disables the client's built-in rate limit checks. ```go import "github.com/gofri/go-github-ratelimit" rateLimiter, err := github_ratelimit.NewRateLimiter(http.DefaultClient.Transport) if err != nil { log.Fatal(err) } client, err := github.NewClient( github.WithTransport(rateLimiter), github.WithAuthToken(token), github.WithDisableRateLimitCheck(), // Use external limiter instead ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Repository by ID Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Retrieves a repository using its unique numeric ID. Requires context and the repository ID. ```go func (s *RepositoriesService) GetByID(ctx context.Context, id int64) (*Repository, *Response, error) ``` ```go repo, _, err := client.Repositories.GetByID(ctx, 27193779) ``` -------------------------------- ### Detecting AbuseRateLimitError Source: https://github.com/google/go-github/blob/master/_autodocs/errors.md Example of how to check if an error is an AbuseRateLimitError and handle the retry logic based on the RetryAfter field. ```go import "errors" result, _, err := client.Repositories.CreateStatus(ctx, owner, repo, ref, status) var abuseErr *github.AbuseRateLimitError if errors.As(err, &abuseErr) { if abuseErr.RetryAfter != nil { fmt.Printf("Retry after %v\n", *abuseErr.RetryAfter) time.Sleep(*abuseErr.RetryAfter) } else { fmt.Println("Secondary rate limit hit, retry later") } } ``` -------------------------------- ### Import go-github Package Source: https://github.com/google/go-github/blob/master/README.md Import the go-github package into your Go project. This can be done directly in your code, and then 'go get' can be run without parameters. ```go import "github.com/google/go-github/v88/github" ``` -------------------------------- ### Get Repository by Owner and Name Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Retrieves a specific repository using its owner's login and the repository's name. Requires context, owner, and repo name. ```go func (s *RepositoriesService) Get(ctx context.Context, owner, repo string) (*Repository, *Response, error) ``` ```go repo, resp, err := client.Repositories.Get(ctx, "google", "go-github") if err != nil { log.Fatal(err) } fmt.Printf("Repository: %s\n", repo.GetFullName()) fmt.Printf("Stars: %d\n", repo.GetStargazersCount()) fmt.Printf("Language: %s\n", repo.GetLanguage()) ``` -------------------------------- ### Detecting RedirectionError Source: https://github.com/google/go-github/blob/master/_autodocs/errors.md Example of how to detect a RedirectionError and log the redirection details, including the original response and the target location. ```go import "errors" resp, err := client.bareDoIgnoreRedirects(req) var redirectErr *github.RedirectionError if errors.As(err, &redirectErr) { fmt.Printf("Redirect from %s to %s\n", resp.Request.URL, redirectErr.Location) } ``` -------------------------------- ### GitHub Client with Optional Parameters Source: https://github.com/google/go-github/blob/master/README.md Make API calls with optional parameters to filter or modify the results. This example lists public repositories for the 'github' organization. ```go import "github.com/google/go-github/v88/github" import "context" func main() { client, err := github.NewClient() if err != nil { // Handle error. } // list public repositories for org "github" opt := &github.RepositoryListByOrgOptions{Type: "public"} repos, _, err := client.Repositories.ListByOrg(context.Background(), "github", opt) } ``` -------------------------------- ### Go Doc Comment for Exported Type Source: https://github.com/google/go-github/blob/master/CONTRIBUTING.md Example of a Go doc comment for an exported type, providing a concise description of the type's purpose. ```go // Repository represents a GitHub repository. type Repository struct { ID *int64 `json:"id,omitempty"` NodeID *string `json:"node_id,omitempty"` Owner *User `json:"owner,omitempty"` // ... } ``` -------------------------------- ### Go Doc Comment for Exported Method Source: https://github.com/google/go-github/blob/master/CONTRIBUTING.md Example of a Go doc comment for an exported method, including a short description, GitHub API documentation link, and a meta-operation directive for code generation. ```go // Get fetches a repository. // // GitHub API docs: https://docs.github.com/rest/repos/repos?apiVersion=2022-11-28#get-a-repository // //meta:operation GET /repos/{owner}/{repo} func (s *RepositoriesService) Get(ctx context.Context, owner, repo string) (*Repository, *Response, error) { u := fmt.Sprintf("repos/%v/%v", owner, repo) req, err := s.client.NewRequest(ctx, "GET", u, nil) // ... } ``` -------------------------------- ### Get User Agent String Source: https://github.com/google/go-github/blob/master/_autodocs/client.md Retrieve the User-Agent header string that the client uses when making requests to the GitHub API. ```go func (c *Client) UserAgent() string ``` -------------------------------- ### Authenticate as GitHub App with go-githubauth Source: https://github.com/google/go-github/blob/master/README.md Use go-githubauth to create an OAuth2 client for authenticating as a GitHub App installation. This method is useful when interacting with APIs that require OAuth authentication, such as writing to a repository. ```go package main import ( "context" "fmt" "os" "strconv" "github.com/google/go-github/v88/github" "github.com/jferrl/go-githubauth" "golang.org/x/oauth2" ) func main() { privateKey := []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY")) appTokenSource, err := githubauth.NewApplicationTokenSource(1112, privateKey) if err != nil { fmt.Println("Error creating application token source:", err) return } installationTokenSource := githubauth.NewInstallationTokenSource(1113, appTokenSource) // oauth2.NewClient uses oauth2.ReuseTokenSource to reuse the token until it expires. // The token will be automatically refreshed when it expires. // InstallationTokenSource has the mechanism to refresh the token when it expires. httpClient := oauth2.NewClient(context.Background(), installationTokenSource) client, err := github.NewClient(github.WithHTTPClient(httpClient)) if err != nil { // Handle error. } } ``` -------------------------------- ### Initialize Go GitHub Client and Access Services Source: https://github.com/google/go-github/blob/master/_autodocs/INDEX.md Demonstrates how to create a new GitHub client with authentication and access common services like Repositories, Issues, and Users. Ensure you have a valid authentication token. ```go client, err := github.NewClient(github.WithAuthToken(token)) if err != nil { log.Fatal(err) } // Access services client.Repositories.Get(ctx, owner, repo) client.Issues.List(ctx, owner, repo, opts) client.Users.Get(ctx, username) ``` -------------------------------- ### Using ListOptions for Offset Pagination Source: https://github.com/google/go-github/blob/master/_autodocs/types.md Shows how to configure ListOptions for fetching repositories by organization and how to iterate through all available pages. ```go opts := &github.ListOptions{ Page: 1, PerPage: 50, } repos, resp, err := client.Repositories.ListByOrg(ctx, "google", opts) // Iterate through all pages for { // Process repos... if resp.NextPage == 0 { break } opts.Page = resp.NextPage repos, resp, err = client.Repositories.ListByOrg(ctx, "google", opts) } ``` -------------------------------- ### Create Production-Ready Client Source: https://github.com/google/go-github/blob/master/_autodocs/configuration.md Creates a production-ready GitHub client with authentication, timeout, user agent, and environment proxy settings. ```go client, err := github.NewClient( github.WithAuthToken(os.Getenv("GITHUB_TOKEN")), github.WithTimeout(30 * time.Second), github.WithUserAgent("MyApp/1.0.0"), github.WithEnvProxy(), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Merge Status Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/pulls.md Checks if a pull request can be merged. ```APIDOC ## Get Merge Status ### Description Checks if a pull request can be merged. Returns true if mergeable. ### Method GET ### Endpoint /repos/{owner}/{repo}/pulls/{pull_number}/merge ### Parameters #### Path Parameters - **owner** (string) - Required - Repository owner - **repo** (string) - Required - Repository name - **number** (int) - Required - Pull request number #### Query Parameters - **opt** (*PullRequestMergeOptions) - Optional - Merge options ### Response #### Success Response (200) - **bool** - True if the pull request is mergeable. - **response** (*Response) - HTTP response metadata ### Request Example ```go canMerge, _, err := client.PullRequests.GetMergeStatus(ctx, "owner", "repo", 123, nil) if canMerge { fmt.Println("PR can be merged") } ``` ``` -------------------------------- ### Get User by ID Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/users.md Retrieves a user by their unique identifier. ```APIDOC ## GET /user/{id} ### Description Gets a user by their ID. ### Method GET ### Endpoint /user/{id} ### Parameters #### Path Parameters - **id** (int64) - Required - User ID #### Query Parameters None #### Request Body None ### Request Example ```go user, _, err := client.Users.GetByID(ctx, 1) if err != nil { log.Fatal(err) } fmt.Printf("User: %s\n", user.GetLogin()) ``` ### Response #### Success Response (200) - **user** (*User) - User data - **response** (*Response) - HTTP response metadata #### Response Example ```json { "login": "octocat", "id": 1, "avatar_url": "https://github.com/images/error/octocat_happy.gif", "name": "The Octocat" } ``` ``` -------------------------------- ### Get Pull Request Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/pulls.md Retrieves a single pull request from a repository by its number. ```APIDOC ## Get Pull Request ### Description Gets a single pull request from a repository. ### Method GET ### Endpoint /repos/{owner}/{repo}/pulls/{pull_number} ### Parameters #### Path Parameters - **owner** (string) - Required - Repository owner - **repo** (string) - Required - Repository name - **number** (int) - Required - Pull request number ### Response #### Success Response (200) - **pr** (*PullRequest) - Pull request data - **response** (*Response) - HTTP response metadata ### Request Example ```go pr, _, err := client.PullRequests.Get(ctx, "kubernetes", "kubernetes", 123) if err != nil { log.Fatal(err) } fmt.Printf("PR: %s\n", pr.GetTitle()) ``` ``` -------------------------------- ### List User Repositories with Options Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Lists all repositories for a given user, supporting filtering and sorting via RepositoryListByUserOptions. Handles pagination to retrieve all results. ```go type RepositoryListByUserOptions struct { Type string // "all", "owner", "public", "private", "member" Sort string // "created", "updated", "pushed", "full_name" Direction string // "asc" or "desc" ListOptions } ``` ```go func (s *RepositoriesService) ListByUser(ctx context.Context, user string, opts *RepositoryListByUserOptions) ([]*Repository, *Response, error) ``` ```go opts := &github.RepositoryListByUserOptions{ Type: "public", Sort: "updated", ListOptions: github.ListOptions{PerPage: 50}, } repos, resp, err := client.Repositories.ListByUser(ctx, "torvalds", opts) // Iterate through all pages for { for _, repo := range repos { fmt.Printf("%s (%s)\n", repo.GetName(), repo.GetLanguage()) } if resp.NextPage == 0 { break } opts.Page = resp.NextPage repos, resp, _ = client.Repositories.ListByUser(ctx, "torvalds", opts) } ``` -------------------------------- ### Get go-github Library Version Source: https://github.com/google/go-github/blob/master/_autodocs/client.md This constant provides the current version of the go-github library. ```go const Version = "v88.0.0" ``` -------------------------------- ### Create GitHub Client Source: https://github.com/google/go-github/blob/master/_autodocs/README.md Demonstrates how to create both unauthenticated and authenticated GitHub clients using go-github. Use an authentication token for authenticated clients. ```go package main import ( "context" "github.com/google/go-github/v88/github" ) func main() { // Create an unauthenticated client client, err := github.NewClient() if err != nil { panic(err) } // Create an authenticated client with a token client, err = github.NewClient( github.WithAuthToken("your_token_here"), ) if err != nil { panic(err) } // Use the client ctx := context.Background() user, _, err := client.Users.Get(ctx, "willnorris") } ``` -------------------------------- ### Get Organization by Name Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Retrieves detailed information about a specific GitHub organization using its name. ```APIDOC ## Get Organization by Name ### Description Gets information about an organization. ### Method GET ### Endpoint /orgs/{org} ### Parameters #### Path Parameters - **org** (string) - Required - Organization name #### Request Example ```go org, _, err := client.Organizations.Get(ctx, "kubernetes") if err != nil { log.Fatal(err) } fmt.Printf("Organization: %s\n", org.GetLogin()) ``` ### Response #### Success Response (200) - **organization** (*Organization) - Organization data - **response** (*Response) - HTTP response metadata - **error** (error) - Error if request failed ``` -------------------------------- ### Get Organization by ID Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Retrieves detailed information about a specific GitHub organization using its unique ID. ```APIDOC ## Get Organization by ID ### Description Gets an organization by ID. ### Method GET ### Endpoint /organizations/{id} ### Parameters #### Path Parameters - **id** (int64) - Required - Organization ID #### Request Example ```go org, _, err := client.Organizations.GetByID(ctx, 1) ``` ### Response #### Success Response (200) - **organization** (*Organization) - Organization data - **response** (*Response) - HTTP response metadata - **error** (error) - Error if request failed ``` -------------------------------- ### Create GitHub Enterprise Client Source: https://github.com/google/go-github/blob/master/_autodocs/configuration.md Instantiate a GitHub client for an enterprise instance. Use this when interacting with GitHub Enterprise Server. ```go client, err := github.NewClient( github.WithEnterpriseURLs("https://github.company.com", "https://github.company.com"), github.WithAuthToken(enterpriseToken), github.WithTimeout(30 * time.Second), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### RepositoriesService.Get Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Gets a specific repository by its owner and name. This method allows you to retrieve detailed information about a single repository. ```APIDOC ## RepositoriesService.Get ### Description Gets a repository by owner and name. ### Method GET ### Endpoint /repos/{owner}/{repo} ### Parameters #### Path Parameters - **owner** (string) - Yes - Repository owner login - **repo** (string) - Yes - Repository name #### Query Parameters None #### Request Body None ### Request Example ```go repo, resp, err := client.Repositories.Get(ctx, "google", "go-github") if err != nil { log.Fatal(err) } fmt.Printf("Repository: %s\n", repo.GetFullName()) fmt.Printf("Stars: %d\n", repo.GetStargazersCount()) fmt.Printf("Language: %s\n", repo.GetLanguage()) ``` ### Response #### Success Response (200) - **repository** (*Repository) - Repository data - **response** (*Response) - HTTP response metadata #### Response Example ```json { "example": "{\"id\": 12345, \"name\": \"go-github\", \"full_name\": \"google/go-github\", ...}" } ``` ``` -------------------------------- ### Create Basic Authenticated Client Source: https://github.com/google/go-github/blob/master/_autodocs/configuration.md Creates a new GitHub client authenticated with a token from the GITHUB_TOKEN environment variable. ```go client, err := github.NewClient( github.WithAuthToken(os.Getenv("GITHUB_TOKEN")), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Create User or Organization Repository Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Creates a new repository. If the organization is empty, it creates a repository for the authenticated user. Otherwise, it creates an organization repository. ```go newRepo := &github.Repository{ Name: github.Ptr("new-repo"), Description: github.Ptr("My new repository"), Private: github.Ptr(true), HasIssues: github.Ptr(true), HasProjects: github.Ptr(true), HasWiki: github.Ptr(false), } repo, _, err := client.Repositories.Create(ctx, "", newRepo) if err != nil { log.Fatal(err) } // Create organization repository orgRepo := &github.Repository{ Name: github.Ptr("org-repo"), Private: github.Ptr(true), TeamID: github.Ptr(int64(123)), } repo, _, err = client.Repositories.Create(ctx, "my-org", orgRepo) ``` -------------------------------- ### Create Client with Custom HTTP Configuration Source: https://github.com/google/go-github/blob/master/_autodocs/configuration.md Configure a GitHub client with a custom `http.Client` for fine-grained control over network settings like timeouts and connection pooling. ```go httpClient := &http.Client{ Timeout: 30 * time.Second, Transport: &http.Transport{ MaxIdleConns: 100, MaxIdleConnsPerHost: 100, DialContext: (&net.Dialer{ Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, }).DialContext, IdleConnTimeout: 90 * time.Second, TLSHandshakeTimeout: 10 * time.Second, }, } client, err := github.NewClient( github.WithHTTPClient(httpClient), github.WithAuthToken(token), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Upload API URL Source: https://github.com/google/go-github/blob/master/_autodocs/client.md Retrieve the base URL specifically configured for file upload API requests. ```go func (c *Client) UploadURL() string ``` -------------------------------- ### Using Response Type Source: https://github.com/google/go-github/blob/master/_autodocs/types.md Demonstrates how to access repository data and pagination/rate limit information from a Response object. ```go repos, resp, err := client.Repositories.List(ctx, "", nil) if err == nil { fmt.Printf("Got %d repos\n", len(repos)) fmt.Printf("Has next page: %v\n", resp.NextPage > 0) fmt.Printf("Rate limit remaining: %d\n", resp.Rate.Remaining) fmt.Printf("Token expires: %v\n", resp.TokenExpiration.Time) } ``` -------------------------------- ### ListMembers Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Lists organization members. This method corresponds to the GitHub API endpoint GET /orgs/{org}/members. ```APIDOC ## ListMembers ### Description Lists organization members. ### Method GET ### Endpoint `/orgs/{org}/members` ### Parameters #### Path Parameters - **org** (string) - Required - Organization name #### Query Parameters - **opts** (*ListMembersOptions) - Optional - Filtering and pagination options - **Filter** (string) - Optional - "all", "2fa_disabled" (default: "all") - **Role** (string) - Optional - "all", "admin", "member" (default: "all") ### Response #### Success Response (200) - **members** ([]*User) - Slice of member users - **response** (*Response) - HTTP response with pagination info ### Request Example ```go opts := &github.ListMembersOptions{ Role: "admin", } members, _, err := client.Organizations.ListMembers(ctx, "kubernetes", opts) for _, member := range members { fmt.Printf("%s\n", member.GetLogin()) } ``` ``` -------------------------------- ### Get a Single Repository Branch Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Retrieves details for a specific branch within a repository. Logs an error if the branch cannot be fetched. ```go branch, _, err := client.Repositories.GetBranch(ctx, "google", "go-github", "main") if err != nil { log.Fatal(err) } fmt.Printf("Branch: %s\nSHA: %s\n", branch.GetName(), branch.Commit.GetSHA()) if branch.GetProtected() { fmt.Println("Branch is protected") } ``` -------------------------------- ### Run Integration Tests Source: https://github.com/google/go-github/blob/master/test/README.md Execute integration tests for the go-github library against the live GitHub API. Requires an authentication token. ```bash GITHUB_AUTH_TOKEN=XXX go test -v -tags=integration ./integration ``` -------------------------------- ### List User Repositories Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Lists all repositories for the authenticated user. Supports filtering by visibility and affiliation. ```go repos, _, err := client.Repositories.ListByAuthenticatedUser(ctx, &github.RepositoryListByAuthenticatedUserOptions{ Visibility: "private", Affiliation: "owner", }) ``` -------------------------------- ### Configure Client with Custom URLs Source: https://github.com/google/go-github/blob/master/_autodocs/configuration.md Sets custom base and upload URLs for the client. This is useful for on-premise GitHub Enterprise. Nil values are ignored and defaults are used. ```go baseURL := "https://custom.github.com/api/v3/" uploadURL := "https://uploads.custom.github.com/api/uploads/" client, err := github.NewClient( github.WithURLs(&baseURL, &uploadURL), github.WithAuthToken(token), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### ListPublicMembers Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Lists public members of an organization. This method corresponds to the GitHub API endpoint GET /orgs/{org}/public_members. ```APIDOC ## GET /orgs/{org}/public_members ### Description Lists public members of an organization. ### Method GET ### Endpoint /orgs/{org}/public_members ### Parameters #### Path Parameters - **org** (string) - Required - Organization name #### Query Parameters - **opts** (*ListOptions) - No - Pagination options ### Response #### Success Response (200) - **members** ([]*User) - Slice of public members - **response** (*Response) - HTTP response with pagination info ``` -------------------------------- ### ListByUser Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Lists organizations that a user is a member of. This method corresponds to the GitHub API endpoint GET /users/{username}/orgs. ```APIDOC ## ListByUser ### Description Lists organizations that a user is a member of. ### Method GET ### Endpoint `/users/{username}/orgs` ### Parameters #### Path Parameters - **user** (string) - Required - GitHub username #### Query Parameters - **opts** (*ListOptions) - Optional - Pagination options ### Response #### Success Response (200) - **organizations** ([]*Organization) - Slice of organizations - **response** (*Response) - HTTP response with pagination info ### Request Example ```go orgs, _, err := client.Organizations.ListByUser(ctx, "octocat", nil) for _, org := range orgs { fmt.Printf("%s\n", org.GetLogin()) } ``` ``` -------------------------------- ### Using ListCursorOptions for Cursor Pagination Source: https://github.com/google/go-github/blob/master/_autodocs/types.md Demonstrates fetching global security advisories with cursor pagination and how to retrieve the next page using the cursor from the response. ```go opts := &github.ListCursorOptions{ PerPage: 50, After: "", // Start from beginning } advisories, resp, err := client.SecurityAdvisories.ListGlobal(ctx, opts) // Get next page using cursor opts.After = resp.Cursor advisories, resp, err = client.SecurityAdvisories.ListGlobal(ctx, opts) ``` -------------------------------- ### Get a Single Issue Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/issues.md Retrieves a single issue from a repository. Requires context, owner, repository name, and the issue number. ```go issue, _, err := client.Issues.Get(ctx, "google", "go-github", 123) if err != nil { log.Fatal(err) } fmt.Printf("Issue: %s\n", issue.GetTitle()) fmt.Printf("State: %s\n", issue.GetState()) fmt.Printf("Assignees: %d\n", len(issue.Assignees)) ``` -------------------------------- ### Get Organization by ID Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Retrieves an organization's details using its unique numerical ID. This is an alternative to fetching by name. ```go func (s *OrganizationsService) GetByID(ctx context.Context, id int64) (*Organization, *Response, error) ``` ```go org, _, err := client.Organizations.GetByID(ctx, 1) ``` -------------------------------- ### Using Timestamp Type Source: https://github.com/google/go-github/blob/master/_autodocs/types.md Shows how to access and format timestamps from user data, demonstrating both direct access to the time.Time value and using its Format method. ```go user, _, _ := client.Users.Get(ctx, "octocat") fmt.Println(user.CreatedAt.Time) fmt.Println(user.UpdatedAt.Format("2006-01-02")) ``` -------------------------------- ### ListContributorsStats Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Gets contributor statistics for a repository. This operation may return an `AcceptedError` if the statistics are not yet computed, requiring a subsequent retry. ```APIDOC ## ListContributorsStats ### Description Gets contributor statistics for a repository. May return `AcceptedError` if statistics are not yet computed. ### Method GET ### Endpoint /repos/{owner}/{repo}/stats/contributors ### Parameters #### Path Parameters - **owner** (string) - Required - Repository owner - **repo** (string) - Required - Repository name #### Query Parameters None #### Request Body None ### Request Example ```go stats, _, err := client.Repositories.ListContributorsStats(ctx, "google", "go-github") var acceptedErr *github.AcceptedError if errors.As(err, &acceptedErr) { // Stats not ready yet, retry later time.Sleep(5 * time.Second) stats, _, err = client.Repositories.ListContributorsStats(ctx, "google", "go-github") } if err == nil { for _, cs := range stats { fmt.Printf("%s: %d commits\n", cs.Author.GetLogin(), cs.Total) } } ``` ### Response #### Success Response (200) - **stats** ([]*ContributorStats) - Slice of contributor statistics - **response** (*Response) - HTTP response metadata #### Response Example ```json [ { "author": { "login": "octocat", "id": 1, "node_id": "MDQ6VXNlcjE=", "avatar_url": "https://github.com/images/icons/icon-person.gif", "gravatar_id": "", "url": "https://api.github.com/users/octocat", "html_url": "https://github.com/octocat", "followers_url": "https://api.github.com/users/octocat/followers", "following_url": "https://api.github.com/users/octocat/following{/other_user}", "gists_url": "https://api.github.com/users/octocat/gists{/gist_id}", "starred_url": "https://api.github.com/users/octocat/starred{/owner}{/repo}", "subscriptions_url": "https://api.github.com/users/octocat/subscriptions", "organizations_url": "https://api.github.com/users/octocat/orgs", "repos_url": "https://api.github.com/users/octocat/repos", "events_url": "https://api.github.com/users/octocat/events{/privacy}", "received_events_url": "https://api.github.com/users/octocat/received_events", "type": "User", "site_admin": false }, "total": 100, "weeks": [ { "w": 1677721600, "a": 10, "d": 5, "c": 15 } ] } ] ``` ``` -------------------------------- ### Create a New File in a Repository Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Creates a new file in a specified repository. Requires file content, commit message, and optionally committer details. ```go opts := &github.RepositoryContentFileOptions{ Message: github.Ptr("Create new file"), Content: []byte("File content here"), Branch: github.Ptr("main"), Committer: &github.CommitAuthor{ Name: github.Ptr("My Bot"), Email: github.Ptr("bot@example.com"), }, } resp, _, err := client.Repositories.CreateFile(ctx, "owner", "repo", "path/to/file.txt", opts) ``` -------------------------------- ### List All Issues Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/issues.md Lists issues assigned to the authenticated user across all visible repositories. Use filtering and pagination options to refine the results. ```go opts := &github.ListAllIssuesOptions{ State: "open", Sort: "updated", Direction: "desc", ListOptions: github.ListOptions{PerPage: 30}, } issues, resp, err := client.Issues.ListAllIssues(ctx, opts) for _, issue := range issues { fmt.Printf("#%d %s\n", issue.GetNumber(), issue.GetTitle()) } ``` -------------------------------- ### Get a Single Repository Commit Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Retrieves details for a specific commit in a repository using its SHA. Useful for inspecting commit history. ```go commit, _, err := client.Repositories.GetCommit(ctx, "google", "go-github", "abc123def456") if err != nil { log.Fatal(err) } fmt.Printf("Author: %s\n", commit.Commit.Author.Name) fmt.Printf("Message: %s\n", commit.Commit.Message) ``` -------------------------------- ### IsMember Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Checks if a user is a member of an organization. This method corresponds to the GitHub API endpoint GET /orgs/{org}/members/{username}. ```APIDOC ## IsMember ### Description Checks if a user is a member of an organization. ### Method GET ### Endpoint `/orgs/{org}/members/{username}` ### Parameters #### Path Parameters - **org** (string) - Required - Organization name - **username** (string) - Required - GitHub username ### Response #### Success Response (200) - **member** (bool) - True if user is a member - **response** (*Response) - HTTP response metadata ### Request Example ```go isMember, _, err := client.Organizations.IsMember(ctx, "google", "octocat") if isMember { fmt.Println("User is a member") } ``` ``` -------------------------------- ### Generate Release Notes Source: https://github.com/google/go-github/blob/master/README.md Generate release notes by running the provided tool script. Specify the previous tag using the --tag flag. ```bash go run tools/gen-release-notes/main.go --tag v88.0.0 ``` -------------------------------- ### Get Issue Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/issues.md Retrieves a single issue from a specified repository. This operation requires the repository owner, repository name, and the issue number. ```APIDOC ## GET /repos/{owner}/{repo}/issues/{issue_number} ### Description Gets a single issue from a repository. ### Method GET ### Endpoint `/repos/{owner}/{repo}/issues/{issue_number}` ### Parameters #### Path Parameters - **owner** (string) - Required - Repository owner - **repo** (string) - Required - Repository name - **number** (int) - Required - Issue number ### Response #### Success Response (200) - **issue** (*Issue) - Issue data ### Request Example ```go issue, _, err := client.Issues.Get(ctx, "google", "go-github", 123) if err != nil { log.Fatal(err) } fmt.Printf("Issue: %s\n", issue.GetTitle()) fmt.Printf("State: %s\n", issue.GetState()) fmt.Printf("Assignees: %d\n", len(issue.Assignees)) ``` ``` -------------------------------- ### Get User Information Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/users.md Retrieves public user information. If the user string is empty, it returns the authenticated user's information. ```APIDOC ## GET /users/{username} or GET /user (authenticated) ### Description Gets public user information. If the user string is empty, returns the authenticated user's information. ### Method GET ### Endpoint /users/{username} or /user ### Parameters #### Path Parameters - **username** (string) - Required - GitHub username (empty for authenticated user) #### Query Parameters None #### Request Body None ### Request Example ```go // Get public user information user, _, err := client.Users.Get(ctx, "octocat") if err != nil { log.Fatal(err) } fmt.Printf("User: %s\n", user.GetLogin()) fmt.Printf("Name: %s\n", user.GetName()) fmt.Printf("Followers: %d\n", user.GetFollowers()) fmt.Printf("Following: %d\n", user.GetFollowing()) // Get authenticated user information user, _, err = client.Users.Get(ctx, "") if err != nil { log.Fatal(err) } fmt.Printf("Current user: %s\n", user.GetLogin()) ``` ### Response #### Success Response (200) - **user** (*User) - User data - **response** (*Response) - HTTP response metadata #### Response Example ```json { "login": "octocat", "id": 12345, "avatar_url": "https://github.com/images/error/octocat_happy.gif", "name": "The Octocat", "company": "GitHub", "followers": 100, "following": 5 } ``` ``` -------------------------------- ### Configure Client with Environment Proxy Source: https://github.com/google/go-github/blob/master/_autodocs/configuration.md Configures the client to use HTTP proxy settings from environment variables. Without this option, the client ignores environment proxy settings. ```go client, err := github.NewClient( github.WithEnvProxy(), github.WithAuthToken(token), ) if err != nil { log.Fatal(err) } ``` -------------------------------- ### Get Repository File Contents Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Retrieves the content of a file or directory within a GitHub repository. The content is base64 encoded and needs to be decoded. ```go content, _, err := client.Repositories.GetContents(ctx, "google", "go-github", "README.md", nil) if err != nil { log.Fatal(err) } // Decode content (base64 encoded) decoded, err := content.GetContent() if err != nil { log.Fatal(err) } fmt.Println(decoded) ``` -------------------------------- ### Create Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Creates a new repository. Can be for the authenticated user or an organization. ```APIDOC ## Create ### Description Creates a new repository. If `org` is empty, creates a repository for the authenticated user. If `org` is specified, creates an organization repository. ### Method POST ### Endpoint /user/repos or /orgs/{org}/repos ### Parameters #### Path Parameters - **org** (string) - No - Organization name (empty for user repo). #### Request Body - **repo** (*Repository) - Yes - Repository configuration. - **Name** (string) - Required - The name of the repository. - **Description** (string) - Optional - The description of the repository. - **Private** (bool) - Optional - Whether the repository is private. - **HasIssues** (bool) - Optional - Whether to enable issues. - **HasProjects** (bool) - Optional - Whether to enable projects. - **HasWiki** (bool) - Optional - Whether to enable the wiki. - **TeamID** (int64) - Optional - The ID of the team to associate with the repository (for organization repositories). ### Request Example ```go newRepo := &github.Repository{ Name: github.Ptr("new-repo"), Description: github.Ptr("My new repository"), Private: github.Ptr(true), HasIssues: github.Ptr(true), HasProjects: github.Ptr(true), HasWiki: github.Ptr(false), } repo, _, err := client.Repositories.Create(ctx, "", newRepo) // Create organization repository orgRepo := &github.Repository{ Name: github.Ptr("org-repo"), Private: github.Ptr(true), TeamID: github.Ptr(int64(123)), } repo, _, err = client.Repositories.Create(ctx, "my-org", orgRepo) ``` ### Response #### Success Response (201) - **repository** (*Repository) - Created repository data. - **response** (*Response) - HTTP response metadata. ``` -------------------------------- ### IsPublicMember Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Checks if a user is a public member of an organization. This method corresponds to the GitHub API endpoint GET /orgs/{org}/public_members/{username}. ```APIDOC ## GET /orgs/{org}/public_members/{username} ### Description Checks if a user is a public member of an organization. ### Method GET ### Endpoint /orgs/{org}/public_members/{username} ### Parameters #### Path Parameters - **org** (string) - Required - Organization name - **username** (string) - Required - GitHub username ### Response #### Success Response (200) - **public** (bool) - True if user is a public member - **response** (*Response) - HTTP response metadata ``` -------------------------------- ### List All Organizations Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Fetches a list of all organizations, ordered by creation date. Supports pagination for handling large numbers of organizations. ```go func (s *OrganizationsService) ListAll(ctx context.Context, opts *ListOptions) ([]*Organization, *Response, error) ``` ```go orgs, resp, err := client.Organizations.ListAll(ctx, &github.ListOptions{ PerPage: 50, }) for _, org := range orgs { fmt.Printf("%s: %s\n", org.GetLogin(), org.GetDescription()) } ``` -------------------------------- ### List Repository Branches with Options Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Lists branches in a repository, with options to filter by protection status. Requires BranchListOptions struct. ```go opts := &github.BranchListOptions{ Protected: github.Ptr(true), } branches, _, err := client.Repositories.ListBranches(ctx, "owner", "repo", opts) ``` -------------------------------- ### Getting Rate Limit Information Source: https://github.com/google/go-github/blob/master/_autodocs/types.md Retrieves the current rate limits for various API resources and prints their status. Useful for monitoring API usage. ```go limits, resp, err := client.RateLimit.Get(ctx) if err == nil { for _, rate := range limits { fmt.Printf("%s: %d/%d remaining (resets at %v)\n", rate.Resource, rate.Remaining, rate.Limit, rate.Reset.Time) } } ``` -------------------------------- ### Get Organization by Name Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/organizations.md Retrieves detailed information about a specific organization using its name. Ensure you have the organization's login name to use this method. ```go func (s *OrganizationsService) Get(ctx context.Context, org string) (*Organization, *Response, error) ``` ```go org, _, err := client.Organizations.Get(ctx, "kubernetes") if err != nil { log.Fatal(err) } fmt.Printf("Organization: %s\n", org.GetLogin()) fmt.Printf("Members: %d\n", org.GetPublicMembers()) fmt.Printf("Description: %s\n", org.GetDescription()) ``` -------------------------------- ### List Organization Repositories Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/repositories.md Lists all repositories for a given organization. Supports filtering by type and sorting. Requires authentication to list private repositories. ```go repos, _, err := client.Repositories.ListByOrg(ctx, "kubernetes", &github.RepositoryListByOrgOptions{ Type: "public", Sort: "stars", }) ``` -------------------------------- ### Get Underlying HTTP Client Source: https://github.com/google/go-github/blob/master/_autodocs/client.md Retrieve the `http.Client` instance used internally by the GitHub client. This client is pre-configured with authorization headers and should only be used for API requests. ```go func (c *Client) Client() *http.Client ``` -------------------------------- ### Get GitHub User by ID Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/users.md Retrieves a user's information using their unique GitHub ID. This function requires a context and the user's ID. ```go user, _, err := client.Users.GetByID(ctx, 1) if err != nil { log.Fatal(err) } fmt.Printf("User: %s\n", user.GetLogin()) ``` -------------------------------- ### Handle Rate Limits in Go-GitHub Source: https://github.com/google/go-github/blob/master/_autodocs/errors.md Choose between letting the client handle retries automatically using context or implementing manual retry logic with exponential backoff and sleep durations based on the reset time. ```go // Option 1: Let client handle retries ctx := context.WithValue(context.Background(), github.SleepUntilPrimaryRateLimitResetWhenRateLimited, true) user, _, err := client.Users.Get(ctx, "octocat") ``` ```go // Option 2: Manual retry logic for attempts := 0; attempts < 3; attempts++ { user, resp, err := client.Users.Get(ctx, "octocat") var rateLimitErr *github.RateLimitError if errors.As(err, &rateLimitErr) { waitTime := time.Until(rateLimitErr.Rate.Reset.Time) log.Printf("Rate limited, waiting %v", waitTime) time.Sleep(waitTime) continue } // Check for other errors or success break } ``` -------------------------------- ### Get a Single Pull Request Source: https://github.com/google/go-github/blob/master/_autodocs/api-reference/pulls.md Retrieves a specific pull request from a repository by its number. Requires context, owner, repository name, and the pull request number. ```go pr, _, err := client.PullRequests.Get(ctx, "kubernetes", "kubernetes", 123) if err != nil { log.Fatal(err) } fmt.Printf("PR: %s\n", pr.GetTitle()) fmt.Printf("State: %s\n", pr.GetState()) fmt.Printf("Commits: %d\n", pr.GetCommits()) fmt.Printf("Additions: %d, Deletions: %d\n", pr.GetAdditions(), pr.GetDeletions()) ``` -------------------------------- ### UploadOptions Struct Source: https://github.com/google/go-github/blob/master/_autodocs/types.md Defines parameters for uploading files, such as release assets. Use this to specify the file name, label, and media type for uploads. ```go type UploadOptions struct { Name string `url:"name,omitempty"` Label string `url:"label,omitempty"` MediaType string `url:"-"` } ``` ```go file, err := os.Open("release.tar.gz") deferr file.Close() upload := &github.UploadOptions{ Name: "release.tar.gz", Label: "Source code archive", MediaType: "application/gzip", } asset, _, err := client.Repositories.UploadReleaseAsset(ctx, owner, repo, releaseID, upload, file) ```