{"id":13367177,"url":"https://github.com/Google/Go-github","last_synced_at":"2025-03-12T18:32:00.265Z","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":"2024-10-27T13:06:12.000Z","size":7800,"stargazers_count":10423,"open_issues_count":83,"forks_count":2056,"subscribers_count":207,"default_branch":"master","last_synced_at":"2024-10-29T19:58:58.469Z","etag":null,"topics":["github","github-api","go","golang","hacktoberfest"],"latest_commit_sha":null,"homepage":"https://pkg.go.dev/github.com/google/go-github/v66/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}},"created_at":"2013-05-24T16:42:58.000Z","updated_at":"2024-10-29T11:05:24.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":125,"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":243271476,"owners_count":20264463,"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-30T00:01:40.656Z","updated_at":"2025-03-12T18:32:00.259Z","avatar_url":"https://github.com/google.png","language":"Go","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/v69/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.21 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/v69\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/v69/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/v69@master\n```\n\n## Usage ##\n\n```go\nimport \"github.com/google/go-github/v69/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 cancelation 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/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/v69/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/v69/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 a rate limit on all API clients. Unauthenticated clients are\nlimited to 60 requests per hour, while authenticated clients can make up to\n5,000 requests per hour. The Search API has a custom rate limit. Unauthenticated\nclients are limited to 10 requests per minute, while authenticated clients\ncan make up to 30 requests per minute. To receive the higher rate limit when\nmaking calls that are not issued on behalf of a user,\nuse `UnauthenticatedRateLimitedTransport`.\n\nThe 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 `RateLimits` to fetch the most up-to-date rate\nlimit data for the client.\n\nTo detect an API rate limit error, you can check if its type is `*github.RateLimitError`:\n\n```go\nrepos, _, err := client.Repositories.List(ctx, \"\", nil)\nif _, ok := err.(*github.RateLimitError); ok {\n\tlog.Println(\"hit rate limit\")\n}\n```\n\nLearn more about GitHub rate limiting in\n[\"REST API endpoints for rate limits\"](https://docs.github.com/en/rest/rate-limit).\n\nIn addition to these rate limits, GitHub imposes a secondary rate limit on all API clients.\nThis rate limit prevents clients from making too many concurrent requests.\n\nTo detect an API secondary rate limit error, you can check if its type is `*github.AbuseRateLimitError`:\n\n```go\nrepos, _, err := client.Repositories.List(ctx, \"\", nil)\nif _, ok := err.(*github.AbuseRateLimitError); ok {\n\tlog.Println(\"hit secondary rate limit\")\n}\n```\n\nAlternatively, you can block until the rate limit is reset by using the `context.WithValue` method:\n\n```go\nrepos, _, err := client.Repositories.List(context.WithValue(ctx, github.SleepUntilPrimaryRateLimitResetWhenRateLimited, true), \"\", nil)\n```\n\nYou can use [gofri/go-github-ratelimit](https://github.com/gofri/go-github-ratelimit) to handle\nsecondary rate limit sleep-and-retry for you.\n\nLearn more about GitHub secondary rate limiting in\n[\"About secondary rate limits\"](https://docs.github.com/en/rest/using-the-rest-api/rate-limits-for-the-rest-api?apiVersion=2022-11-28#about-secondary-rate-limits).\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 _, ok := err.(*github.AcceptedError); ok {\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 7234](https://datatracker.ietf.org/doc/html/rfc7234)\ncompliant HTTP cache such as [gregjones/httpcache](https://github.com/gregjones/httpcache)\nis recommended, ex:\n\n```go\nimport \"github.com/gregjones/httpcache\"\n\nclient := github.NewClient(\n\thttpcache.NewMemoryCacheTransport().Client()\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### 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/v69/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| 69.x.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","funding_links":[],"categories":["第三方 APIs"],"sub_categories":["高級控制台界面","高级控制台界面"],"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"}