go-github
moduleThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
README¶
go-github
go-github is a Go client library for accessing theGitHub API v3.
Currently,go-github requires Go version 1.13 or greater. go-github tracksGo's version support policy. We do our best not to breakolder versions of Go if we don't have to, but due to tooling constraints, wedon't always test older versions.
If you're interested in using theGraphQL API v4, the recommended library isshurcooL/githubv4.
Installation
go-github is compatible with modern Go releases in module mode, with Go installed:
go get github.com/google/go-github/v43
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/v43/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/v43@master
Usage
import "github.com/google/go-github/v43/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 the GitHub API documentation athttps://docs.github.com/en/free-pro-team@latest/rest/reference/.
NOTE: Using thecontext package, one can easilypass cancelation 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.
Authentication
The go-github library does not directly handle authentication. Instead, whencreating a new client, pass anhttp.Client
that can handle authentication foryou. The easiest and recommended way to do this is using theoauth2library, but you can always use any other library that provides anhttp.Client
. If you have an OAuth2 access token (for example, apersonalAPI token), you can use it with the oauth2 library using:
import "golang.org/x/oauth2"func main() {ctx := context.Background()ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "... your access token ..."},)tc := oauth2.NewClient(ctx, ts)client := github.NewClient(tc)// list all repositories for the authenticated userrepos, _, err := client.Repositories.List(ctx, "", nil)}
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.
See theoauth2 docs for complete instructions on using that library.
For API methods that require HTTP Basic Authentication, use theBasicAuthTransport
.
GitHub Apps authentication can be provided by theghinstallationpackage.
import ("github.com/bradleyfalzon/ghinstallation/v2""github.com/google/go-github/v43/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")if err != nil {// Handle error.}// Use installation transport with client.client := github.NewClient(&http.Client{Transport: itr})// Use client...}
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.
Rate Limiting
GitHub imposes a rate limit on all API clients. Unauthenticated clients arelimited to 60 requests per hour, while authenticated clients can make up to5,000 requests per hour. The Search API has a custom rate limit. Unauthenticatedclients are limited to 10 requests per minute, while authenticated clientscan make up to 30 requests per minute. To receive the higher rate limit whenmaking calls that are not issued on behalf of a user,useUnauthenticatedRateLimitedTransport
.
The returnedResponse.Rate
value contains the rate limit informationfrom the most recent API call. If a recent enough response isn'tavailable, you can useRateLimits
to fetch the most up-to-date ratelimit data for the client.
To detect an API rate limit error, you can check if its type is*github.RateLimitError
:
repos, _, err := client.Repositories.List(ctx, "", nil)if _, ok := err.(*github.RateLimitError); ok {log.Println("hit rate limit")}
Learn more about GitHub rate limiting athttps://docs.github.com/en/free-pro-team@latest/rest/reference/rate-limit.
Accepted Status
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)if _, ok := err.(*github.AcceptedError); ok {log.Println("scheduled on GitHub side")}
Conditional Requests
The GitHub API has good support for conditional requests which will helpprevent you from burning through your rate limit, as well as help speed up yourapplication.go-github
does not handle conditional requests directly, but isinstead designed to work with a cachinghttp.Transport
. We recommend usinghttps://github.com/gregjones/httpcache for that.
Learn more about GitHub conditional requests athttps://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#conditional-requests.
Creating and Updating Resources
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.String("foo"),Private: github.Bool(true),}client.Repositories.Create(ctx, "", repo)
Users who have worked with protocol buffers should find this pattern familiar.
Pagination
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 resultsvar allRepos []*github.Repositoryfor {repos, resp, err := client.Repositories.ListByOrg(ctx, "github", opt)if err != nil {return err}allRepos = append(allRepos, repos...)if resp.NextPage == 0 {break}opt.Page = resp.NextPage}
For complete usage of go-github, see the fullpackage docs.
Testing code that usesgo-github
The repomigueleliasweb/go-github-mock provides a way to mock responses. Check the repo for more details.
Integration Tests
You can run integration tests from thetest
directory. See the integration testsREADME.
Contributing
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.
Versioning
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.
License
This library is distributed under the BSD-style license found in theLICENSEfile.
Directories¶
Path | Synopsis |
---|---|
example | |
appengine Package demo provides an app that shows how to use the github package on Google App Engine. | Package demo provides an app that shows how to use the github package on Google App Engine. |
basicauthcommand The basicauth command demonstrates using the github.BasicAuthTransport, including handling two-factor authentication. | The basicauth command demonstrates using the github.BasicAuthTransport, including handling two-factor authentication. |
commitprcommand The commitpr command utilizes go-github as a CLI tool for pushing files to a branch and creating a pull request from it. | The commitpr command utilizes go-github as a CLI tool for pushing files to a branch and creating a pull request from it. |
listenvironmentscommand listenvironments is an example of how to use ListEnvironments method with EnvironmentListOptions. | listenvironments is an example of how to use ListEnvironments method with EnvironmentListOptions. |
migrationscommand migrations demonstrates the functionality of the user data migration API for the authenticated GitHub user and lists all the user migrations. | migrations demonstrates the functionality of the user data migration API for the authenticated GitHub user and lists all the user migrations. |
newfilewithappauthcommand newfilewithappauth demonstrates the functionality of GitHub's app authentication methods by fetching an installation access token and reauthenticating to GitHub with OAuth configurations. | newfilewithappauth demonstrates the functionality of GitHub's app authentication methods by fetching an installation access token and reauthenticating to GitHub with OAuth configurations. |
newrepocommand The newrepo command utilizes go-github as a cli tool for creating new repositories. | The newrepo command utilizes go-github as a cli tool for creating new repositories. |
simplecommand The simple command demonstrates a simple functionality which prompts the user for a GitHub username and lists all the public organization memberships of the specified username. | The simple command demonstrates a simple functionality which prompts the user for a GitHub username and lists all the public organization memberships of the specified username. |
tokenauthcommand The tokenauth command demonstrates using the oauth2.StaticTokenSource. | The tokenauth command demonstrates using the oauth2.StaticTokenSource. |
topicscommand The simple command demonstrates the functionality that prompts the user for a GitHub topic and lists all the entities that are related to the specified topic or subject. | The simple command demonstrates the functionality that prompts the user for a GitHub topic and lists all the entities that are related to the specified topic or subject. |
Package github provides a client for using the GitHub API. | Package github provides a client for using the GitHub API. |
test | |
fieldscommand This tool tests for the JSON mappings in the go-github data types. | This tool tests for the JSON mappings in the go-github data types. |
integration Package integration contains integration tests. | Package integration contains integration tests. |