Get GitHub repository's organization

237 Views Asked by At

I'm trying to list a user's repos and get the organizations they belong to using go-github.

These repositories belong to an organization, but the organization values seem to be nil.

Code:

import "github.com/google/go-github/v37/github"

func GetClient(token) *GitHub {
    ctx := context.Background()
    ts := oauth2.StaticTokenSource(
        &oauth2.Token{AccessToken: token},
    )
    tc := oauth2.NewClient(ctx, ts)
    client := github.NewClient(tc)

    return client
}

func main() {
    client := GetClient("TOKEN")

    repos, _, err := client.Repositories.List(context.TODO(), "", nil)
    if err != nil {
        log.Fatal(err)
    }

    for _, repo := range repos {
        println(*repo.Name)
        org := repo.GetOrganization()
        println(org)
        println(repo.Organization)
    }
}

Output:

api
0x0
0x0
api-inserter
0x0
0x0
bbprograms
0x0
0x0
console-api
0x0
0x0
console-spa

I know for a fact that these repos are part of an organization the user belongs to.

1

There are 1 best solutions below

0
On

You could just call the API directly:

package main

import (
   "encoding/json"
   "fmt"
   "net/http"
)

func main() {
   r, err := http.Get("https://api.github.com/users/bradfitz/orgs")
   if err != nil {
      panic(err)
   }
   defer r.Body.Close()
   var orgs []struct{Login string}
   json.NewDecoder(r.Body).Decode(&orgs)
   fmt.Printf("%+v\n", orgs) // [{Login:djabberd} {Login:camlistore} {Login:tailscale}]
}

https://docs.github.com/en/rest/reference/users