{"id":13414021,"url":"https://github.com/google/go-github","last_synced_at":"2026-01-06T03:16:13.034Z","repository":{"id":8626210,"uuid":"10270722","full_name":"google/go-github","owner":"google","description":"Go library for accessing the GitHub v3 API","archived":false,"fork":false,"pushed_at":"2025-04-30T12:27:36.000Z","size":9202,"stargazers_count":10783,"open_issues_count":36,"forks_count":2130,"subscribers_count":206,"default_branch":"master","last_synced_at":"2025-05-05T14:07:14.034Z","etag":null,"topics":["github","github-api","go","golang","hacktoberfest"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/google/go-github/v71/github","language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/google.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":"AUTHORS","dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2013-05-24T16:42:58.000Z","updated_at":"2025-05-04T15:03:34.000Z","dependencies_parsed_at":"2023-10-01T19:31:36.069Z","dependency_job_id":"b08162b1-cb24-453d-9066-d53d77ace668","html_url":"https://github.com/google/go-github","commit_stats":{"total_commits":2261,"total_committers":771,"mean_commits":"2.9325551232166016","dds":0.8275099513489607,"last_synced_commit":"78ac52d48290d8960e46177e43cfe820aca262b7"},"previous_names":[],"tags_count":132,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fgo-github","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fgo-github/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fgo-github/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/google%2Fgo-github/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/google","download_url":"https://codeload.github.com/google/go-github/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253557084,"owners_count":21927176,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["github","github-api","go","golang","hacktoberfest"],"created_at":"2024-07-30T20:01:55.427Z","updated_at":"2026-01-06T03:16:13.029Z","avatar_url":"https://github.com/google.png","language":"Go","funding_links":[],"categories":["Popular","Go","开源类库","Misc","Third-party APIs","Programming","Go (134)","Open source library","网络服务","第三方 API","Repositories","第三方api","第三方API","Utility","\u003cspan id=\"第三方api-third-party-apis\"\u003e第三方API Third-party APIs\u003c/span\u003e","第三方API`第三方API 汇总`"],"sub_categories":["Git","Utility/Miscellaneous","Golang","Advanced Console UIs","网络服务_其他","HTTP Clients","爬虫工具","实用程序/Miscellaneous","Fail injection","交流","\u003cspan id=\"高级控制台用户界面-advanced-console-uis\"\u003e高级控制台用户界面 Advanced Console UIs\u003c/span\u003e","查询语"],"readme":"# go-github #\n\n[![go-github release (latest SemVer)](https://img.shields.io/github/v/release/google/go-github?sort=semver)](https://github.com/google/go-github/releases)\n[![Go Reference](https://img.shields.io/static/v1?label=godoc\u0026message=reference\u0026color=blue)](https://pkg.go.dev/github.com/google/go-github/v80/github)\n[![Test Status](https://github.com/google/go-github/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/google/go-github/actions/workflows/tests.yml)\n[![Test Coverage](https://codecov.io/gh/google/go-github/branch/master/graph/badge.svg)](https://codecov.io/gh/google/go-github)\n[![Discuss at go-github@googlegroups.com](https://img.shields.io/badge/discuss-go--github%40googlegroups.com-blue.svg)](https://groups.google.com/group/go-github)\n[![CII Best Practices](https://bestpractices.coreinfrastructure.org/projects/796/badge)](https://bestpractices.coreinfrastructure.org/projects/796)\n\ngo-github is a Go client library for accessing the [GitHub API v3][].\n\ngo-github tracks [Go's version support policy][support-policy] supporting any\nminor version of the latest two major releases of Go and the go directive in\ngo.mod reflects that.\nWe do our best not to break older versions of Go if we don't have to, but we\ndon't explicitly test older versions and as of Go 1.23 the go directive in\ngo.mod declares a hard required _minimum_ version of Go to use with this module\nand this _must_ be greater than or equal to the go line of all dependencies so\ngo-github will require the N-1 major release of Go by default.\n\n[support-policy]: https://golang.org/doc/devel/release.html#policy\n\n## Development\n\nIf you're interested in using the [GraphQL API v4][], the recommended library is\n[shurcooL/githubv4][].\n\n## Installation ##\n\ngo-github is compatible with modern Go releases in module mode, with Go installed:\n\n```bash\ngo get github.com/google/go-github/v80\n```\n\nwill resolve and add the package to the current development module, along with its dependencies.\n\nAlternatively the same can be achieved if you use import in a package:\n\n```go\nimport \"github.com/google/go-github/v80/github\"\n```\n\nand run `go get` without parameters.\n\nFinally, to use the top-of-trunk version of this repo, use the following command:\n\n```bash\ngo get github.com/google/go-github/v80@master\n```\n\n## Usage ##\n\n```go\nimport \"github.com/google/go-github/v80/github\"\t// with go modules enabled (GO111MODULE=on or outside GOPATH)\nimport \"github.com/google/go-github/github\" // with go modules disabled\n```\n\nConstruct a new GitHub client, then use the various services on the client to\naccess different parts of the GitHub API. For example:\n\n```go\nclient := github.NewClient(nil)\n\n// list all organizations for user \"willnorris\"\norgs, _, err := client.Organizations.List(context.Background(), \"willnorris\", nil)\n```\n\nSome API methods have optional parameters that can be passed. For example:\n\n```go\nclient := github.NewClient(nil)\n\n// list public repositories for org \"github\"\nopt := \u0026github.RepositoryListByOrgOptions{Type: \"public\"}\nrepos, _, err := client.Repositories.ListByOrg(context.Background(), \"github\", opt)\n```\n\nThe services of a client divide the API into logical chunks and correspond to\nthe structure of the [GitHub API documentation](https://docs.github.com/en/rest).\n\nNOTE: Using the [context](https://pkg.go.dev/context) package, one can easily\npass cancellation signals and deadlines to various services of the client for\nhandling a request. In case there is no context available, then `context.Background()`\ncan be used as a starting point.\n\nFor more sample code snippets, head over to the\n[example](https://github.com/google/go-github/tree/master/example) directory.\n\n### Authentication ###\n\nUse the `WithAuthToken` method to configure your client to authenticate using an\nOAuth token (for example, a [personal access token][]). This is what is needed\nfor a majority of use cases aside from GitHub Apps.\n\n```go\nclient := github.NewClient(nil).WithAuthToken(\"... your access token ...\")\n```\n\nNote that when using an authenticated Client, all calls made by the client will\ninclude the specified OAuth token. Therefore, authenticated clients should\nalmost never be shared between different users.\n\nFor API methods that require HTTP Basic Authentication, use the\n[`BasicAuthTransport`](https://pkg.go.dev/github.com/google/go-github/v80/github#BasicAuthTransport).\n\n#### As a GitHub App ####\n\nGitHub Apps authentication can be provided by different pkgs like [bradleyfalzon/ghinstallation](https://github.com/bradleyfalzon/ghinstallation)\nor [jferrl/go-githubauth](https://github.com/jferrl/go-githubauth).\n\n\u003e **Note**: Most endpoints (ex. [`GET /rate_limit`]) require access token authentication\n\u003e while a few others (ex. [`GET /app/hook/deliveries`]) require [JWT] authentication.\n\n[`GET /rate_limit`]: https://docs.github.com/en/rest/rate-limit#get-rate-limit-status-for-the-authenticated-user\n[`GET /app/hook/deliveries`]: https://docs.github.com/en/rest/apps/webhooks#list-deliveries-for-an-app-webhook\n[JWT]: https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app\n\n`ghinstallation` provides `Transport`, which implements `http.RoundTripper` to provide authentication as an installation for GitHub Apps.\n\nHere is an example of how to authenticate as a GitHub App using the `ghinstallation` package:\n\n```go\nimport (\n\t\"net/http\"\n\n\t\"github.com/bradleyfalzon/ghinstallation/v2\"\n\t\"github.com/google/go-github/v80/github\"\n)\n\nfunc main() {\n\t// Wrap the shared transport for use with the integration ID 1 authenticating with installation ID 99.\n\titr, err := ghinstallation.NewKeyFromFile(http.DefaultTransport, 1, 99, \"2016-10-19.private-key.pem\")\n\n\t// Or for endpoints that require JWT authentication\n\t// itr, err := ghinstallation.NewAppsTransportKeyFromFile(http.DefaultTransport, 1, \"2016-10-19.private-key.pem\")\n\n\tif err != nil {\n\t\t// Handle error.\n\t}\n\n\t// Use installation transport with client.\n\tclient := github.NewClient(\u0026http.Client{Transport: itr})\n\n\t// Use client...\n}\n```\n\n`go-githubauth` implements a set of `oauth2.TokenSource` to be used with `oauth2.Client`. An `oauth2.Client` can be injected into the `github.Client` to authenticate requests.\n\nOther example using `go-githubauth`:\n\n```go\npackage main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"os\"\n\t\"strconv\"\n\n\t\"github.com/google/go-github/v80/github\"\n\t\"github.com/jferrl/go-githubauth\"\n\t\"golang.org/x/oauth2\"\n)\n\nfunc main() {\n\tprivateKey := []byte(os.Getenv(\"GITHUB_APP_PRIVATE_KEY\"))\n\n\tappTokenSource, err := githubauth.NewApplicationTokenSource(1112, privateKey)\n\tif err != nil {\n\t\tfmt.Println(\"Error creating application token source:\", err)\n\t\treturn\n\t }\n\n\tinstallationTokenSource := githubauth.NewInstallationTokenSource(1113, appTokenSource)\n\n\t// oauth2.NewClient uses oauth2.ReuseTokenSource to reuse the token until it expires.\n\t// The token will be automatically refreshed when it expires.\n\t// InstallationTokenSource has the mechanism to refresh the token when it expires.\n\thttpClient := oauth2.NewClient(context.Background(), installationTokenSource)\n\n\tclient := github.NewClient(httpClient)\n}\n```\n\n*Note*: In order to interact with certain APIs, for example writing a file to a repo, one must generate an installation token\nusing the installation ID of the GitHub app and authenticate with the OAuth method mentioned above. See the examples.\n\n### Rate Limiting ###\n\nGitHub imposes rate limits on all API clients. The [primary rate limit](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-primary-rate-limits)\nis the limit to the number of REST API requests that a client can make within a\nspecific amount of time. This limit helps prevent abuse and denial-of-service\nattacks, and ensures that the API remains available for all users. Some\nendpoints, like the search endpoints, have more restrictive limits.\nUnauthenticated clients may request public data but have a low rate limit,\nwhile authenticated clients have rate limits based on the client\nidentity.\n\nIn addition to primary rate limits, GitHub enforces [secondary rate limits](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api#about-secondary-rate-limits)\nin order to prevent abuse and keep the API available for all users.\nSecondary rate limits generally limit the number of concurrent requests that a\nclient can make.\n\nThe client returned `Response.Rate` value contains the rate limit information\nfrom the most recent API call. If a recent enough response isn't\navailable, you can use the client `RateLimits` service to fetch the most\nup-to-date rate limit data for the client.\n\nTo detect a primary API rate limit error, you can check if the error is a\n`RateLimitError`.\n\n```go\nrepos, _, err := client.Repositories.List(ctx, \"\", nil)\nvar rateErr *github.RateLimitError\nif errors.As(err, \u0026rateError) {\n\tlog.Printf(\"hit primary rate limit, used %v of %v\\n\", rateErr.Rate.Used, rateErr.rate.Limit)\n}\n```\n\nTo detect an API secondary rate limit error, you can check if the error is an\n`AbuseRateLimitError`.\n\n```go\nrepos, _, err := client.Repositories.List(ctx, \"\", nil)\nvar rateErr *github.AbuseRateLimitError\nif errors.As(err, \u0026rateErr) {\n\tlog.Printf(\"hit secondary rate limit, retry after %v\\n\", rateErr.RetryAfter)\n}\n```\n\nIf you hit the primary rate limit, you can use the `SleepUntilPrimaryRateLimitResetWhenRateLimited`\nmethod to block until the rate limit is reset.\n\n```go\nrepos, _, err := client.Repositories.List(context.WithValue(ctx, github.SleepUntilPrimaryRateLimitResetWhenRateLimited, true), \"\", nil)\n```\n\nIf you need to make a request even if the rate limit has been hit you can use\nthe `BypassRateLimitCheck` method to bypass the rate limit check and make the\nrequest anyway.\n\n```go\nrepos, _, err := client.Repositories.List(context.WithValue(ctx, github.BypassRateLimitCheck, true), \"\", nil)\n```\n\nFor more advanced use cases, you can use [gofri/go-github-ratelimit](https://github.com/gofri/go-github-ratelimit)\nwhich provides a middleware (`http.RoundTripper`) that handles both the primary\nrate limit and secondary rate limit for the GitHub API. In this case you can\nset the client `DisableRateLimitCheck` to `true` so the client doesn't track the rate limit usage.\n\nIf the client is an [OAuth app](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api#primary-rate-limit-for-oauth-apps)\nyou can use the apps higher rate limit to request public data by using the\n`UnauthenticatedRateLimitedTransport` to make calls as the app instead of as\nthe user.\n\n### Accepted Status ###\n\nSome endpoints may return a 202 Accepted status code, meaning that the\ninformation required is not yet ready and was scheduled to be gathered on\nthe GitHub side. Methods known to behave like this are documented specifying\nthis behavior.\n\nTo detect this condition of error, you can check if its type is\n`*github.AcceptedError`:\n\n```go\nstats, _, err := client.Repositories.ListContributorsStats(ctx, org, repo)\nif errors.As(err, new(*github.AcceptedError)) {\n\tlog.Println(\"scheduled on GitHub side\")\n}\n```\n\n### Conditional Requests ###\n\nThe GitHub REST API has good support for [conditional HTTP requests](https://docs.github.com/en/rest/using-the-rest-api/best-practices-for-using-the-rest-api?apiVersion=2022-11-28#use-conditional-requests-if-appropriate)\nvia the `ETag` header which will help prevent you from burning through your\nrate limit, as well as help speed up your application. `go-github` does not\nhandle conditional requests directly, but is instead designed to work with a\ncaching `http.Transport`.\n\nTypically, an [RFC 9111](https://datatracker.ietf.org/doc/html/rfc9111)\ncompliant HTTP cache such as [bartventer/httpcache](https://github.com/bartventer/httpcache)\nis recommended, ex:\n\n```go\nimport (\n\t\"github.com/bartventer/httpcache\"\n\t_ \"github.com/bartventer/httpcache/store/memcache\" //  Register the in-memory backend\n)\n\nclient := github.NewClient(\n\thttpcache.NewClient(\"memcache://\"),\n).WithAuthToken(os.Getenv(\"GITHUB_TOKEN\"))\n```\n\nAlternatively, the [bored-engineer/github-conditional-http-transport](https://github.com/bored-engineer/github-conditional-http-transport)\npackage relies on (undocumented) GitHub specific cache logic and is\nrecommended when making requests using short-lived credentials such as a \n[GitHub App installation token](https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation).\n\n### Creating and Updating Resources ###\n\nAll structs for GitHub resources use pointer values for all non-repeated fields.\nThis allows distinguishing between unset fields and those set to a zero-value.\nHelper functions have been provided to easily create these pointers for string,\nbool, and int values. For example:\n\n```go\n// create a new private repository named \"foo\"\nrepo := \u0026github.Repository{\n\tName:    github.Ptr(\"foo\"),\n\tPrivate: github.Ptr(true),\n}\nclient.Repositories.Create(ctx, \"\", repo)\n```\n\nUsers who have worked with protocol buffers should find this pattern familiar.\n\n### Pagination ###\n\nAll requests for resource collections (repos, pull requests, issues, etc.)\nsupport pagination. Pagination options are described in the\n`github.ListOptions` struct and passed to the list methods directly or as an\nembedded type of a more specific list options struct (for example\n`github.PullRequestListOptions`). Pages information is available via the\n`github.Response` struct.\n\n```go\nclient := github.NewClient(nil)\n\nopt := \u0026github.RepositoryListByOrgOptions{\n\tListOptions: github.ListOptions{PerPage: 10},\n}\n// get all pages of results\nvar allRepos []*github.Repository\nfor {\n\trepos, resp, err := client.Repositories.ListByOrg(ctx, \"github\", opt)\n\tif err != nil {\n\t\treturn err\n\t}\n\tallRepos = append(allRepos, repos...)\n\tif resp.NextPage == 0 {\n\t\tbreak\n\t}\n\topt.Page = resp.NextPage\n}\n```\n\n#### Iterators (**experimental**) ####\n\nGo v1.23 introduces the new `iter` package.  \n\nWith the `enrichman/gh-iter` package, it is possible to create iterators for `go-github`. The iterator will handle pagination for you, looping through all the available results.\n\n```go\nclient := github.NewClient(nil)\nvar allRepos []*github.Repository\n\n// create an iterator and start looping through all the results\nrepos := ghiter.NewFromFn1(client.Repositories.ListByOrg, \"github\")\nfor repo := range repos.All() {\n\tallRepos = append(allRepos, repo)\n}\n```\n\nFor complete usage of `enrichman/gh-iter`, see the full [package docs](https://github.com/enrichman/gh-iter).\n\n#### Middleware ####\n\nYou can use [gofri/go-github-pagination](https://github.com/gofri/go-github-pagination) to handle\npagination for you. It supports both sync and async modes, as well as customizations.  \nBy default, the middleware automatically paginates through all pages, aggregates results, and returns them as an array.  \nSee `example/ratelimit/main.go` for usage.\n\n### Webhooks ###\n\n`go-github` provides structs for almost all [GitHub webhook events][] as well as functions to validate them and unmarshal JSON payloads from `http.Request` structs.\n\n```go\nfunc (s *GitHubEventMonitor) ServeHTTP(w http.ResponseWriter, r *http.Request) {\n\tpayload, err := github.ValidatePayload(r, s.webhookSecretKey)\n\tif err != nil { ... }\n\tevent, err := github.ParseWebHook(github.WebHookType(r), payload)\n\tif err != nil { ... }\n\tswitch event := event.(type) {\n\tcase *github.CommitCommentEvent:\n\t\tprocessCommitCommentEvent(event)\n\tcase *github.CreateEvent:\n\t\tprocessCreateEvent(event)\n\t...\n\t}\n}\n```\n\nFurthermore, there are libraries like [cbrgm/githubevents][] that build upon the example above and provide functions to subscribe callbacks to specific events.\n\nFor complete usage of go-github, see the full [package docs][].\n\n[GitHub API v3]: https://docs.github.com/en/rest\n[personal access token]: https://github.com/blog/1509-personal-api-tokens\n[package docs]: https://pkg.go.dev/github.com/google/go-github/v80/github\n[GraphQL API v4]: https://developer.github.com/v4/\n[shurcooL/githubv4]: https://github.com/shurcooL/githubv4\n[GitHub webhook events]: https://docs.github.com/en/developers/webhooks-and-events/webhooks/webhook-events-and-payloads\n[cbrgm/githubevents]: https://github.com/cbrgm/githubevents\n\n### Testing code that uses `go-github` ###\n\nThe repo [migueleliasweb/go-github-mock](https://github.com/migueleliasweb/go-github-mock) provides a way to mock responses. Check the repo for more details.\n\n### Integration Tests ###\n\nYou can run integration tests from the `test` directory. See the integration tests [README](test/README.md).\n\n## Contributing ##\n\nI would like to cover the entire GitHub API and contributions are of course always welcome. The\ncalling pattern is pretty well established, so adding new methods is relatively\nstraightforward. See [`CONTRIBUTING.md`](CONTRIBUTING.md) for details.\n\n## Versioning ##\n\nIn general, go-github follows [semver](https://semver.org/) as closely as we\ncan for tagging releases of the package. For self-contained libraries, the\napplication of semantic versioning is relatively straightforward and generally\nunderstood. But because go-github is a client library for the GitHub API, which\nitself changes behavior, and because we are typically pretty aggressive about\nimplementing preview features of the GitHub API, we've adopted the following\nversioning policy:\n\n* We increment the **major version** with any incompatible change to\n\tnon-preview functionality, including changes to the exported Go API surface\n\tor behavior of the API.\n* We increment the **minor version** with any backwards-compatible changes to\n\tfunctionality, as well as any changes to preview functionality in the GitHub\n\tAPI. GitHub makes no guarantee about the stability of preview functionality,\n\tso neither do we consider it a stable part of the go-github API.\n* We increment the **patch version** with any backwards-compatible bug fixes.\n\nPreview functionality may take the form of entire methods or simply additional\ndata returned from an otherwise non-preview method. Refer to the GitHub API\ndocumentation for details on preview functionality.\n\n### Calendar Versioning ###\n\nAs of 2022-11-28, GitHub [has announced](https://github.blog/2022-11-28-to-infinity-and-beyond-enabling-the-future-of-githubs-rest-api-with-api-versioning/)\nthat they are starting to version their v3 API based on \"calendar-versioning\".\n\nIn practice, our goal is to make per-method version overrides (at\nleast in the core library) rare and temporary.\n\nOur understanding of the GitHub docs is that they will be revving the\nentire API to each new date-based version, even if only a few methods\nhave breaking changes. Other methods will accept the new version with\ntheir existing functionality. So when a new date-based version of the\nGitHub API is released, we (the repo maintainers) plan to:\n\n* update each method that had breaking changes, overriding their\n  per-method API version header. This may happen in one or multiple\n  commits and PRs, and is all done in the main branch.\n\n* once all of the methods with breaking changes have been updated,\n  have a final commit that bumps the default API version, and remove\n  all of the per-method overrides. That would now get a major version\n  bump when the next go-github release is made.\n\n### Version Compatibility Table ###\n\nThe following table identifies which version of the GitHub API is\nsupported by this (and past) versions of this repo (go-github).\nVersions prior to 48.2.0 are not listed.\n\n| go-github Version | GitHub v3 API Version |\n| ----------------- | --------------------- |\n| 80.0.0            | 2022-11-28            |\n| ...               | 2022-11-28            |\n| 48.2.0            | 2022-11-28            |\n\n## License ##\n\nThis library is distributed under the BSD-style license found in the [LICENSE](./LICENSE)\nfile.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogle%2Fgo-github","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgoogle%2Fgo-github","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgoogle%2Fgo-github/lists"}