- Notifications
You must be signed in to change notification settings - Fork2.2k
Go library for accessing the GitHub v3 API
License
google/go-github
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
go-github is a Go client library for accessing theGitHub API v3.
go-github tracksGo's version support policy supporting anyminor version of the latest two major releases of Go and the go directive ingo.mod reflects that.We do our best not to break older versions of Go if we don't have to, but wedon't explicitly test older versions and as of Go 1.23 the go directive ingo.mod declares a hard requiredminimum version of Go to use with this moduleand thismust be greater than or equal to the go line of all dependencies sogo-github will require the N-1 major release of Go by default.
If you're interested in using theGraphQL API v4, the recommended library isshurcooL/githubv4.
go-github is compatible with modern Go releases in module mode, with Go installed:
go get github.com/google/go-github/v80
will resolve and add the package to the current development module, along with its dependencies.
Alternatively the same can be achieved if you use import in a package:
import"github.com/google/go-github/v80/github"
and rungo get without parameters.
Finally, to use the top-of-trunk version of this repo, use the following command:
go get github.com/google/go-github/v80@master
import"github.com/google/go-github/v80/github"// with go modules enabled (GO111MODULE=on or outside GOPATH)import"github.com/google/go-github/github"// with go modules disabled
Construct a new GitHub client, then use the various services on the client toaccess different parts of the GitHub API. For example:
client:=github.NewClient(nil)// list all organizations for user "willnorris"orgs,_,err:=client.Organizations.List(context.Background(),"willnorris",nil)
Some API methods have optional parameters that can be passed. For example:
client:=github.NewClient(nil)// list public repositories for org "github"opt:=&github.RepositoryListByOrgOptions{Type:"public"}repos,_,err:=client.Repositories.ListByOrg(context.Background(),"github",opt)
The services of a client divide the API into logical chunks and correspond tothe structure of theGitHub API documentation.
NOTE: Using thecontext package, one can easilypass cancellation signals and deadlines to various services of the client forhandling a request. In case there is no context available, thencontext.Background()can be used as a starting point.
For more sample code snippets, head over to theexample directory.
Use theWithAuthToken method to configure your client to authenticate using anOAuth token (for example, apersonal access token). This is what is neededfor a majority of use cases aside from GitHub Apps.
client:=github.NewClient(nil).WithAuthToken("... your access token ...")
Note that when using an authenticated Client, all calls made by the client willinclude the specified OAuth token. Therefore, authenticated clients shouldalmost never be shared between different users.
For API methods that require HTTP Basic Authentication, use theBasicAuthTransport.
GitHub Apps authentication can be provided by different pkgs likebradleyfalzon/ghinstallationorjferrl/go-githubauth.
Note: Most endpoints (ex.
GET /rate_limit) require access token authenticationwhile a few others (ex.GET /app/hook/deliveries) requireJWT authentication.
ghinstallation providesTransport, which implementshttp.RoundTripper to provide authentication as an installation for GitHub Apps.
Here is an example of how to authenticate as a GitHub App using theghinstallation package:
import ("net/http""github.com/bradleyfalzon/ghinstallation/v2""github.com/google/go-github/v80/github")funcmain() {// 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")iferr!=nil {// Handle error.}// Use installation transport with client.client:=github.NewClient(&http.Client{Transport:itr})// Use client...}
go-githubauth implements a set ofoauth2.TokenSource to be used withoauth2.Client. Anoauth2.Client can be injected into thegithub.Client to authenticate requests.
Other example usinggo-githubauth:
package mainimport ("context""fmt""os""strconv""github.com/google/go-github/v80/github""github.com/jferrl/go-githubauth""golang.org/x/oauth2")funcmain() {privateKey:= []byte(os.Getenv("GITHUB_APP_PRIVATE_KEY"))appTokenSource,err:=githubauth.NewApplicationTokenSource(1112,privateKey)iferr!=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:=github.NewClient(httpClient)}
Note: In order to interact with certain APIs, for example writing a file to a repo, one must generate an installation tokenusing the installation ID of the GitHub app and authenticate with the OAuth method mentioned above. See the examples.
GitHub imposes rate limits on all API clients. Theprimary rate limitis the limit to the number of REST API requests that a client can make within aspecific amount of time. This limit helps prevent abuse and denial-of-serviceattacks, and ensures that the API remains available for all users. Someendpoints, like the search endpoints, have more restrictive limits.Unauthenticated clients may request public data but have a low rate limit,while authenticated clients have rate limits based on the clientidentity.
In addition to primary rate limits, GitHub enforcessecondary rate limitsin order to prevent abuse and keep the API available for all users.Secondary rate limits generally limit the number of concurrent requests that aclient can make.
The client returnedResponse.Rate value contains the rate limit informationfrom the most recent API call. If a recent enough response isn'tavailable, you can use the clientRateLimits service to fetch the mostup-to-date rate limit data for the client.
To detect a primary API rate limit error, you can check if the error is aRateLimitError.
repos,_,err:=client.Repositories.List(ctx,"",nil)varrateErr*github.RateLimitErroriferrors.As(err,&rateError) {log.Printf("hit primary rate limit, used %v of %v\n",rateErr.Rate.Used,rateErr.rate.Limit)}
To detect an API secondary rate limit error, you can check if the error is anAbuseRateLimitError.
repos,_,err:=client.Repositories.List(ctx,"",nil)varrateErr*github.AbuseRateLimitErroriferrors.As(err,&rateErr) {log.Printf("hit secondary rate limit, retry after %v\n",rateErr.RetryAfter)}
If you hit the primary rate limit, you can use theSleepUntilPrimaryRateLimitResetWhenRateLimitedmethod to block until the rate limit is reset.
repos,_,err:=client.Repositories.List(context.WithValue(ctx,github.SleepUntilPrimaryRateLimitResetWhenRateLimited,true),"",nil)
If you need to make a request even if the rate limit has been hit you can usetheBypassRateLimitCheck method to bypass the rate limit check and make therequest anyway.
repos,_,err:=client.Repositories.List(context.WithValue(ctx,github.BypassRateLimitCheck,true),"",nil)
For more advanced use cases, you can usegofri/go-github-ratelimitwhich provides a middleware (http.RoundTripper) that handles both the primaryrate limit and secondary rate limit for the GitHub API. In this case you canset the clientDisableRateLimitCheck totrue so the client doesn't track the rate limit usage.
If the client is anOAuth appyou can use the apps higher rate limit to request public data by using theUnauthenticatedRateLimitedTransport to make calls as the app instead of asthe user.
Some endpoints may return a 202 Accepted status code, meaning that theinformation required is not yet ready and was scheduled to be gathered onthe GitHub side. Methods known to behave like this are documented specifyingthis behavior.
To detect this condition of error, you can check if its type is*github.AcceptedError:
stats,_,err:=client.Repositories.ListContributorsStats(ctx,org,repo)iferrors.As(err,new(*github.AcceptedError)) {log.Println("scheduled on GitHub side")}
The GitHub REST API has good support forconditional HTTP requestsvia theETag header which will help prevent you from burning through yourrate limit, as well as help speed up your application.go-github does nothandle conditional requests directly, but is instead designed to work with acachinghttp.Transport.
Typically, anRFC 9111compliant HTTP cache such asbartventer/httpcacheis recommended, ex:
import ("github.com/bartventer/httpcache"_"github.com/bartventer/httpcache/store/memcache"// Register the in-memory backend)client:=github.NewClient(httpcache.NewClient("memcache://"),).WithAuthToken(os.Getenv("GITHUB_TOKEN"))
Alternatively, thebored-engineer/github-conditional-http-transportpackage relies on (undocumented) GitHub specific cache logic and isrecommended when making requests using short-lived credentials such as aGitHub App installation token.
All structs for GitHub resources use pointer values for all non-repeated fields.This allows distinguishing between unset fields and those set to a zero-value.Helper functions have been provided to easily create these pointers for string,bool, and int values. For example:
// create a new private repository named "foo"repo:=&github.Repository{Name:github.Ptr("foo"),Private:github.Ptr(true),}client.Repositories.Create(ctx,"",repo)
Users who have worked with protocol buffers should find this pattern familiar.
All requests for resource collections (repos, pull requests, issues, etc.)support pagination. Pagination options are described in thegithub.ListOptions struct and passed to the list methods directly or as anembedded type of a more specific list options struct (for examplegithub.PullRequestListOptions). Pages information is available via thegithub.Response struct.
client:=github.NewClient(nil)opt:=&github.RepositoryListByOrgOptions{ListOptions: github.ListOptions{PerPage:10},}// get all pages of resultsvarallRepos []*github.Repositoryfor {repos,resp,err:=client.Repositories.ListByOrg(ctx,"github",opt)iferr!=nil {returnerr}allRepos=append(allRepos,repos...)ifresp.NextPage==0 {break}opt.Page=resp.NextPage}
Go v1.23 introduces the newiter package.
With theenrichman/gh-iter package, it is possible to create iterators forgo-github. The iterator will handle pagination for you, looping through all the available results.
client:=github.NewClient(nil)varallRepos []*github.Repository// create an iterator and start looping through all the resultsrepos:=ghiter.NewFromFn1(client.Repositories.ListByOrg,"github")forrepo:=rangerepos.All() {allRepos=append(allRepos,repo)}
For complete usage ofenrichman/gh-iter, see the fullpackage docs.
You can usegofri/go-github-pagination to handlepagination for you. It supports both sync and async modes, as well as customizations.
By default, the middleware automatically paginates through all pages, aggregates results, and returns them as an array.
Seeexample/ratelimit/main.go for usage.
go-github provides structs for almost allGitHub webhook events as well as functions to validate them and unmarshal JSON payloads fromhttp.Request structs.
func (s*GitHubEventMonitor)ServeHTTP(w http.ResponseWriter,r*http.Request) {payload,err:=github.ValidatePayload(r,s.webhookSecretKey)iferr!=nil {... }event,err:=github.ParseWebHook(github.WebHookType(r),payload)iferr!=nil {... }switchevent:=event.(type) {case*github.CommitCommentEvent:processCommitCommentEvent(event)case*github.CreateEvent:processCreateEvent(event)...}}
Furthermore, there are libraries likecbrgm/githubevents that build upon the example above and provide functions to subscribe callbacks to specific events.
For complete usage of go-github, see the fullpackage docs.
The repomigueleliasweb/go-github-mock provides a way to mock responses. Check the repo for more details.
You can run integration tests from thetest directory. See the integration testsREADME.
I would like to cover the entire GitHub API and contributions are of course always welcome. Thecalling pattern is pretty well established, so adding new methods is relativelystraightforward. SeeCONTRIBUTING.md for details.
In general, go-github followssemver as closely as wecan for tagging releases of the package. For self-contained libraries, theapplication of semantic versioning is relatively straightforward and generallyunderstood. But because go-github is a client library for the GitHub API, whichitself changes behavior, and because we are typically pretty aggressive aboutimplementing preview features of the GitHub API, we've adopted the followingversioning policy:
- We increment themajor version with any incompatible change tonon-preview functionality, including changes to the exported Go API surfaceor behavior of the API.
- We increment theminor version with any backwards-compatible changes tofunctionality, as well as any changes to preview functionality in the GitHubAPI. GitHub makes no guarantee about the stability of preview functionality,so neither do we consider it a stable part of the go-github API.
- We increment thepatch version with any backwards-compatible bug fixes.
Preview functionality may take the form of entire methods or simply additionaldata returned from an otherwise non-preview method. Refer to the GitHub APIdocumentation for details on preview functionality.
As of 2022-11-28, GitHubhas announcedthat they are starting to version their v3 API based on "calendar-versioning".
In practice, our goal is to make per-method version overrides (atleast in the core library) rare and temporary.
Our understanding of the GitHub docs is that they will be revving theentire API to each new date-based version, even if only a few methodshave breaking changes. Other methods will accept the new version withtheir existing functionality. So when a new date-based version of theGitHub API is released, we (the repo maintainers) plan to:
update each method that had breaking changes, overriding theirper-method API version header. This may happen in one or multiplecommits and PRs, and is all done in the main branch.
once all of the methods with breaking changes have been updated,have a final commit that bumps the default API version, and removeall of the per-method overrides. That would now get a major versionbump when the next go-github release is made.
The following table identifies which version of the GitHub API issupported by this (and past) versions of this repo (go-github).Versions prior to 48.2.0 are not listed.
| go-github Version | GitHub v3 API Version |
|---|---|
| 80.0.0 | 2022-11-28 |
| ... | 2022-11-28 |
| 48.2.0 | 2022-11-28 |
This library is distributed under the BSD-style license found in theLICENSEfile.
About
Go library for accessing the GitHub v3 API
Topics
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.