google/go-github: Go library for accessing the GitHub API

文章推薦指數: 80 %
投票人數:10人

go-github is a Go client library for accessing the GitHub API v3. Currently, go-github requires Go version 1.13 or greater. go-github tracks Go's version ... Skiptocontent {{message}} google / go-github Public Notifications Star 8k Fork 1.7k GolibraryforaccessingtheGitHubAPI pkg.go.dev/github.com/google/go-github/v41/github BSD-3-ClauseLicense 8k stars 1.7k forks Star Notifications Code Issues 26 Pullrequests 8 Actions Security Insights More Code Issues Pullrequests Actions Security Insights master Branches Tags Couldnotloadbranches Nothingtoshow Loading {{refName}} default Couldnotloadtags Nothingtoshow {{refName}} default Loading 2 branches 89 tags Code Loading Latestcommit mengmichael1 UpdatecommentonListPullRequestsWithCommit(#2228) … fef3638 Dec15,2021 UpdatecommentonListPullRequestsWithCommit(#2228) fef3638 Gitstats 1,635 commits Files Permalink Failedtoloadlatestcommitinformation. Type Name Latestcommitmessage Committime .github     example     github     scrape     test     update-urls     .codecov.yml     .gitignore     .golangci.yml     AUTHORS     CONTRIBUTING.md     LICENSE     README.md     go.mod     go.sum     Viewcode go-github Installation Usage Authentication RateLimiting AcceptedStatus ConditionalRequests CreatingandUpdatingResources Pagination Testingcodethatusesgo-github IntegrationTests Contributing Versioning License README.md go-github go-githubisaGoclientlibraryforaccessingtheGitHubAPIv3. Currently,go-githubrequiresGoversion1.13orgreater.go-githubtracks Go'sversionsupportpolicy.Wedoourbestnottobreak olderversionsofGoifwedon'thaveto,butduetotoolingconstraints,we don'talwaystestolderversions. Ifyou'reinterestedinusingtheGraphQLAPIv4,therecommendedlibraryis shurcooL/githubv4. Installation go-githubiscompatiblewithmodernGoreleasesinmodulemode,withGoinstalled: gogetgithub.com/google/go-github/v41 willresolveandaddthepackagetothecurrentdevelopmentmodule,alongwithitsdependencies. Alternativelythesamecanbeachievedifyouuseimportinapackage: import"github.com/google/go-github/v41/github" andrungogetwithoutparameters. Finally,tousethetop-of-trunkversionofthisrepo,usethefollowingcommand: gogetgithub.com/google/go-github/v41@master Usage import"github.com/google/go-github/v41/github" //withgomodulesenabled(GO111MODULE=onoroutsideGOPATH) import"github.com/google/go-github/github"//withgomodulesdisabled ConstructanewGitHubclient,thenusethevariousservicesontheclientto accessdifferentpartsoftheGitHubAPI.Forexample: client:=github.NewClient(nil) //listallorganizationsforuser"willnorris" orgs,_,err:=client.Organizations.List(context.Background(),"willnorris",nil) SomeAPImethodshaveoptionalparametersthatcanbepassed.Forexample: client:=github.NewClient(nil) //listpublicrepositoriesfororg"github" opt:=&github.RepositoryListByOrgOptions{Type:"public"} repos,_,err:=client.Repositories.ListByOrg(context.Background(),"github",opt) TheservicesofaclientdividetheAPIintologicalchunksandcorrespondto thestructureoftheGitHubAPIdocumentationat https://docs.github.com/en/free-pro-team@latest/rest/reference/. NOTE:Usingthecontextpackage,onecaneasily passcancelationsignalsanddeadlinestovariousservicesoftheclientfor handlingarequest.Incasethereisnocontextavailable,thencontext.Background() canbeusedasastartingpoint. Formoresamplecodesnippets,headovertothe exampledirectory. Authentication Thego-githublibrarydoesnotdirectlyhandleauthentication.Instead,when creatinganewclient,passanhttp.Clientthatcanhandleauthenticationfor you.Theeasiestandrecommendedwaytodothisisusingtheoauth2 library,butyoucanalwaysuseanyotherlibrarythatprovidesan http.Client.IfyouhaveanOAuth2accesstoken(forexample,apersonal APItoken),youcanuseitwiththeoauth2libraryusing: import"golang.org/x/oauth2" funcmain(){ ctx:=context.Background() ts:=oauth2.StaticTokenSource( &oauth2.Token{AccessToken:"...youraccesstoken..."}, ) tc:=oauth2.NewClient(ctx,ts) client:=github.NewClient(tc) //listallrepositoriesfortheauthenticateduser repos,_,err:=client.Repositories.List(ctx,"",nil) } NotethatwhenusinganauthenticatedClient,allcallsmadebytheclientwill includethespecifiedOAuthtoken.Therefore,authenticatedclientsshould almostneverbesharedbetweendifferentusers. Seetheoauth2docsforcompleteinstructionsonusingthatlibrary. ForAPImethodsthatrequireHTTPBasicAuthentication,usethe BasicAuthTransport. GitHubAppsauthenticationcanbeprovidedbytheghinstallation package. import"github.com/bradleyfalzon/ghinstallation" funcmain(){ //WrapthesharedtransportforusewiththeintegrationID1authenticatingwithinstallationID99. itr,err:=ghinstallation.NewKeyFromFile(http.DefaultTransport,1,99,"2016-10-19.private-key.pem") iferr!=nil{ //Handleerror. } //Useinstallationtransportwithclient. client:=github.NewClient(&http.Client{Transport:itr}) //Useclient... } RateLimiting GitHubimposesaratelimitonallAPIclients.Unauthenticatedclientsare limitedto60requestsperhour,whileauthenticatedclientscanmakeupto 5,000requestsperhour.TheSearchAPIhasacustomratelimit.Unauthenticated clientsarelimitedto10requestsperminute,whileauthenticatedclients canmakeupto30requestsperminute.Toreceivethehigherratelimitwhen makingcallsthatarenotissuedonbehalfofauser, useUnauthenticatedRateLimitedTransport. ThereturnedResponse.Ratevaluecontainstheratelimitinformation fromthemostrecentAPIcall.Ifarecentenoughresponseisn't available,youcanuseRateLimitstofetchthemostup-to-daterate limitdatafortheclient. TodetectanAPIratelimiterror,youcancheckifitstypeis*github.RateLimitError: repos,_,err:=client.Repositories.List(ctx,"",nil) if_,ok:=err.(*github.RateLimitError);ok{ log.Println("hitratelimit") } LearnmoreaboutGitHubratelimitingat https://docs.github.com/en/free-pro-team@latest/rest/reference/rate-limit. AcceptedStatus Someendpointsmayreturna202Acceptedstatuscode,meaningthatthe informationrequiredisnotyetreadyandwasscheduledtobegatheredon theGitHubside.Methodsknowntobehavelikethisaredocumentedspecifying thisbehavior. Todetectthisconditionoferror,youcancheckifitstypeis *github.AcceptedError: stats,_,err:=client.Repositories.ListContributorsStats(ctx,org,repo) if_,ok:=err.(*github.AcceptedError);ok{ log.Println("scheduledonGitHubside") } ConditionalRequests TheGitHubAPIhasgoodsupportforconditionalrequestswhichwillhelp preventyoufromburningthroughyourratelimit,aswellashelpspeedupyour application.go-githubdoesnothandleconditionalrequestsdirectly,butis insteaddesignedtoworkwithacachinghttp.Transport.Werecommendusing https://github.com/gregjones/httpcacheforthat. LearnmoreaboutGitHubconditionalrequestsat https://docs.github.com/en/free-pro-team@latest/rest/overview/resources-in-the-rest-api#conditional-requests. CreatingandUpdatingResources AllstructsforGitHubresourcesusepointervaluesforallnon-repeatedfields. Thisallowsdistinguishingbetweenunsetfieldsandthosesettoazero-value. Helperfunctionshavebeenprovidedtoeasilycreatethesepointersforstring, bool,andintvalues.Forexample: //createanewprivaterepositorynamed"foo" repo:=&github.Repository{ Name:github.String("foo"), Private:github.Bool(true), } client.Repositories.Create(ctx,"",repo) Userswhohaveworkedwithprotocolbuffersshouldfindthispatternfamiliar. Pagination Allrequestsforresourcecollections(repos,pullrequests,issues,etc.) supportpagination.Paginationoptionsaredescribedinthe github.ListOptionsstructandpassedtothelistmethodsdirectlyorasan embeddedtypeofamorespecificlistoptionsstruct(forexample github.PullRequestListOptions).Pagesinformationisavailableviathe github.Responsestruct. client:=github.NewClient(nil) opt:=&github.RepositoryListByOrgOptions{ ListOptions:github.ListOptions{PerPage:10}, } //getallpagesofresults varallRepos[]*github.Repository for{ repos,resp,err:=client.Repositories.ListByOrg(ctx,"github",opt) iferr!=nil{ returnerr } allRepos=append(allRepos,repos...) ifresp.NextPage==0{ break } opt.Page=resp.NextPage } Forcompleteusageofgo-github,seethefullpackagedocs. Testingcodethatusesgo-github Therepomigueleliasweb/go-github-mockprovidesawaytomockresponses.Checktherepoformoredetails. IntegrationTests Youcanrunintegrationtestsfromthetestdirectory.SeetheintegrationtestsREADME. Contributing IwouldliketocovertheentireGitHubAPIandcontributionsareofcoursealwayswelcome.The callingpatternisprettywellestablished,soaddingnewmethodsisrelatively straightforward.SeeCONTRIBUTING.mdfordetails. Versioning Ingeneral,go-githubfollowssemverascloselyaswe canfortaggingreleasesofthepackage.Forself-containedlibraries,the applicationofsemanticversioningisrelativelystraightforwardandgenerally understood.Butbecausego-githubisaclientlibraryfortheGitHubAPI,which itselfchangesbehavior,andbecausewearetypicallyprettyaggressiveabout implementingpreviewfeaturesoftheGitHubAPI,we'veadoptedthefollowing versioningpolicy: Weincrementthemajorversionwithanyincompatiblechangeto non-previewfunctionality,includingchangestotheexportedGoAPIsurface orbehavioroftheAPI. Weincrementtheminorversionwithanybackwards-compatiblechangesto functionality,aswellasanychangestopreviewfunctionalityintheGitHub API.GitHubmakesnoguaranteeaboutthestabilityofpreviewfunctionality, soneitherdoweconsideritastablepartofthego-githubAPI. Weincrementthepatchversionwithanybackwards-compatiblebugfixes. Previewfunctionalitymaytaketheformofentiremethodsorsimplyadditional datareturnedfromanotherwisenon-previewmethod.RefertotheGitHubAPI documentationfordetailsonpreviewfunctionality. License ThislibraryisdistributedundertheBSD-stylelicensefoundintheLICENSE file. About GolibraryforaccessingtheGitHubAPI pkg.go.dev/github.com/google/go-github/v41/github Topics go github-api Resources Readme License BSD-3-ClauseLicense Codeofconduct Codeofconduct Releases 73 v41.0.0 Latest Nov29,2021 +72releases Usedby4.2k +4,223 Contributors455 +444contributors Languages Go 100.0% Youcan’tperformthatactionatthistime. Yousignedinwithanothertaborwindow.Reloadtorefreshyoursession. Yousignedoutinanothertaborwindow.Reloadtorefreshyoursession.



請為這篇文章評分?