Go-GitHub是訪問GitHub API V3的GO客戶庫。
Go-Github需要GO版本1.17及更高版本,並且對GO版本1.22及更大的GO進行了測試。 Go-Github跟踪GO的版本支持策略。如果不需要,我們會盡最大努力不要破壞GO的舊版本,但是由於工具限制,我們並不總是測試較舊版本的版本。
如果您有興趣使用GraphQl API V4,則推薦的庫是Shurcool/githubv4。
Go-GitHub與Modern Go在模塊模式下兼容,並安裝了GO:
go get github.com/google/go-github/v68將解決並將軟件包添加到當前開發模塊及其依賴項。
或者,如果您在軟件包中使用導入,則可以實現相同的情況:
import "github.com/google/go-github/v68/github"然後go get無參數。
最後,要使用此存儲庫的陷入最高版本,請使用以下命令:
go get github.com/google/go-github/v68@master import "github.com/google/go-github/v68/github" // with go modules enabled (GO111MODULE=on or outside GOPATH)
import "github.com/google/go-github/github" // with go modules disabled構建一個新的GitHub客戶端,然後使用客戶端上的各種服務訪問GitHub API的不同部分。例如:
client := github . NewClient ( nil )
// list all organizations for user "willnorris"
orgs , _ , err := client . Organizations . List ( context . Background (), "willnorris" , nil )一些API方法具有可以傳遞的可選參數。例如:
client := github . NewClient ( nil )
// list public repositories for org "github"
opt := & github. RepositoryListByOrgOptions { Type : "public" }
repos , _ , err := client . Repositories . ListByOrg ( context . Background (), "github" , opt )客戶的服務將API分為邏輯塊,並與GitHub API文檔的結構相對應。
注意:使用上下文軟件包,可以輕鬆地將取消信號和截止日期傳遞給客戶的各種服務,以處理請求。如果沒有可用的上下文,則可以將context.Background()用作起點。
有關更多示例代碼段,請轉到示例目錄。
使用WithAuthToken方法配置客戶端使用OAuth代幣(例如,個人訪問令牌)進行身份驗證。除GitHub應用程序外,這是大多數用例所需的。
client := github . NewClient ( nil ). WithAuthToken ( "... your access token ..." )請注意,使用身份驗證的客戶端時,客戶端的所有呼叫都將包括指定的OAUTH令牌。因此,經過身份驗證的客戶幾乎不應在不同用戶之間共享。
對於需要HTTP基本身份驗證的API方法,請使用BasicAuthTransport 。
GitHub應用程序身份驗證可以由Bradleyfalzon/Ghinstallation或Jferrl/Go-Githubauth等不同的PKG提供。
注意:大多數端點(例如
GET /rate_limit)需要訪問令牌身份驗證,而其他一些(例如GET /app/hook/deliveries)需要JWT身份驗證。
ghinstallation提供了Transport ,該傳輸實現了http.RoundTripper ,以提供身份驗證作為GitHub應用程序的安裝。
這是如何使用ghinstallation軟件包作為GITHUB應用進行身份驗證的示例:
import (
"net/http"
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/google/go-github/v68/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" )
// Or for endpoints that require JWT authentication
// itr, err := ghinstallation.NewAppsTransportKeyFromFile(http.DefaultTransport, 1, "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...
} go-githubauth實現了一組oauth2.TokenSource將與oauth2.Client一起使用。 oauth2.Client可以注入github.Client以身份驗證請求。
使用go-githubauth的其他示例:
package main
import (
"context"
"fmt"
"os"
"strconv"
"github.com/google/go-github/v68/github"
"github.com/jferrl/go-githubauth"
"golang.org/x/oauth2"
)
func main () {
privateKey := [] byte ( os . Getenv ( "GITHUB_APP_PRIVATE_KEY" ))
appTokenSource , err := githubauth . NewApplicationTokenSource ( 1112 , privateKey )
if err != 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 )
}注意:為了與某些API進行交互,例如將文件寫入回購,必須使用GitHub應用程序的安裝ID生成安裝令牌,並使用上面提到的OAUTH方法進行身份驗證。請參閱示例。
GitHub對所有API客戶端施加了率限制。未經驗證的客戶每小時限制60個請求,而經過驗證的客戶每小時最多可提供5,000個請求。搜索API具有自定義費率限制。未經驗證的客戶限制為每分鐘10個請求,而身份驗證的客戶每分鐘最多可彌補30個請求。要在代表用戶發出未發出的呼叫時接收較高的利率限制,請使用UnauthenticatedRateLimitedTransport 。
返回的Response.Rate值包含最新API調用中的速率限制信息。如果最近沒有足夠的響應,您可以使用RateLimits獲取客戶端的最新利率限制數據。
要檢測API率限制錯誤,您可以檢查其類型是否為*github.RateLimitError :
repos , _ , err := client . Repositories . List ( ctx , "" , nil )
if _ , ok := err .( * github. RateLimitError ); ok {
log . Println ( "hit rate limit" )
}在“ REST API端點的利率限制”中了解有關GitHub速率限制的更多信息。
除了這些速率限制外,GitHub還對所有API客戶限制了次要率限制。此速率限制可阻止客戶提出太多並發請求。
要檢測API二級率限制錯誤,您可以檢查其類型是否為*github.AbuseRateLimitError :
repos , _ , err := client . Repositories . List ( ctx , "" , nil )
if _ , ok := err .( * github. AbuseRateLimitError ); ok {
log . Println ( "hit secondary rate limit" )
}另外,您可以阻止使用context.WithValue來重置速率限制。
repos , _ , err := client . Repositories . List ( context . WithValue ( ctx , github . SleepUntilPrimaryRateLimitResetWhenRateLimited , true ), "" , nil )您可以使用Gofri/go-github比例來處理次要費率限制您的睡眠和退休。
在“大約二級利率限制”中了解有關GitHub次要率限制的更多信息。
一些端點可能會返回202個接受的狀態代碼,這意味著所需的信息尚未準備就緒,併計劃收集在Github側。已知的行為方式已被記錄為指定此行為。
為了檢測此錯誤條件,您可以檢查其類型是否為*github.AcceptedError :
stats , _ , err := client . Repositories . ListContributorsStats ( ctx , org , repo )
if _ , ok := err .( * github. AcceptedError ); ok {
log . Println ( "scheduled on GitHub side" )
}GitHub API對有條件的請求有很好的支持,這將有助於防止您燃燒的費率限制,並有助於加快應用程序的速度。 go-github不能直接處理有條件的請求,而是設計用於使用緩存http.Transport 。我們建議對此使用Gregjones/httpcache。例如:
import "github.com/gregjones/httpcache"
client := github . NewClient (
httpcache . NewMemoryCacheTransport (). Client ()
). WithAuthToken ( os . Getenv ( "GITHUB_TOKEN" ))在“如果適當的話使用條件請求”中了解有關GitHub條件請求的更多信息。
GitHub資源的所有結構都為所有未重複的字段使用指針值。這允許區分未設置的字段和設置為零值的字段。已經提供了輔助功能,以輕鬆為字符串,bool和int值創建這些指針。例如:
// create a new private repository named "foo"
repo := & github. Repository {
Name : github . Ptr ( "foo" ),
Private : github . Ptr ( true ),
}
client . Repositories . Create ( ctx , "" , repo )使用協議緩衝區的用戶應該熟悉這種模式。
所有資源收集請求(存儲庫,拉請請求,問題等)都支持分頁。分頁選項在github.ListOptions struct中描述,並直接傳遞到列表方法或作為更特定列表選項struck的嵌入式類型(例如github.PullRequestListOptions )。頁面信息可通過github.Response struct獲得。
client := github . NewClient ( nil )
opt := & github. RepositoryListByOrgOptions {
ListOptions : github. ListOptions { PerPage : 10 },
}
// get all pages of results
var allRepos [] * github. Repository
for {
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
} GO V1.23介紹了新的iter軟件包。
使用enrichman/gh-iter軟件包,可以為go-github創建迭代器。迭代器將為您處理分頁,循環通過所有可用結果。
client := github . NewClient ( nil )
var allRepos [] * github. Repository
// create an iterator and start looping through all the results
repos := ghiter . NewFromFn1 ( client . Repositories . ListByOrg , "github" )
for repo := range repos . All () {
allRepos = append ( allRepos , repo )
}有關enrichman/gh-iter的完整使用,請參閱完整的軟件包文檔。
go-github提供了幾乎所有GitHub Webhook事件的結構,以及函數以驗證它們,並從http.Request結構中刪除JSON有效載荷。
func ( s * GitHubEventMonitor ) ServeHTTP ( w http. ResponseWriter , r * http. Request ) {
payload , err := github . ValidatePayload ( r , s . webhookSecretKey )
if err != nil { ... }
event , err := github . ParseWebHook ( github . WebHookType ( r ), payload )
if err != nil { ... }
switch event := event .( type ) {
case * github. CommitCommentEvent :
processCommitCommentEvent ( event )
case * github. CreateEvent :
processCreateEvent ( event )
...
}
}此外,還有諸如CBRGM/githubevents之類的庫在上面的示例上建立,並提供了訂閱對特定事件的回調的功能。
有關Go-Github的完整使用,請參閱完整的包裝文檔。
go-github的測試代碼Repo Migueliasweb/go-github-Mock提供了一種模擬響應的方法。檢查存儲庫以獲取更多詳細信息。
您可以從test目錄運行集成測試。請參閱“集成測試”。
我想介紹整個GitHub API,並且總是歡迎貢獻。調用模式已經建立得很好,因此添加新方法相對簡單。有關詳細信息,請參見CONTRIBUTING.md 。
通常,go-github盡可能地跟隨SEMVER標記包裝的版本。對於獨立的庫,語義版本的應用相對簡單,並且通常被理解。但是,由於Go-Github是GitHub API的客戶端庫,該客戶庫本身會改變行為,而且由於我們在實施GitHub API的預覽功能方面通常非常積極,因此我們採用了以下版本控制策略:
預覽功能可以採用整個方法的形式,也可以簡單地從其他非瀏覽方法返回的其他數據。有關預覽功能的詳細信息,請參閱GitHub API文檔。
截至2022-11-28,GitHub宣布他們將根據“日曆否定”開始版本的V3 API。
在實踐中,我們的目標是使人均版本覆蓋(至少在核心庫中)稀有和臨時。
我們對GITHUB文檔的理解是,即使只有少數方法有破壞性的更改,它們也將將整個API傳遞到每個基於日期的新版本。其他方法將接受具有現有功能的新版本。因此,當發布GITHUB API的新的基於日期的新版本時,我們(回購維護者)計劃:
更新每個具有破壞更改的方法,從而覆蓋其每手電API版本標頭。這可能發生在一個或多個提交和PR中,並且全部在主分支中完成。
一旦更新了破壞更改的所有方法,就將最終提交撞擊默認的API版本,並刪除所有人均替代。現在,當製作下一個Go-GitHub發行版時,這將會引起主要版本的顛簸。
下表確定了此倉庫(go-github)的此(和過去)版本支持哪個版本的GitHub API。未列出48.2.0之前的版本。
| go-github版本 | GitHub V3 API版本 |
|---|---|
| 68.0.0 | 2022-11-28 |
| ... | 2022-11-28 |
| 48.2.0 | 2022-11-28 |
該庫是根據許可證文件中的BSD式許可分配的。