简体   繁体   中英

Extracting information from go-github Gist type

I have started learning Go and I find it quite interesting so far. As an assignment for myself to get get better at the language, I decided to write a Gister in Go using go-github .

I have been able to get all my Gists using an access token and I am able to print as follows:

package main

import "fmt"
import "github.com/google/go-github/github"
import "code.google.com/p/goauth2/oauth"

func main() {
    t := &oauth.Transport{
        Token: &oauth.Token{AccessToken: "secretaccesstokenhere"},
    }

    client := github.NewClient(t.Client())

    gists, _, err := client.Gists.List("", nil)

    if err != nil {
        fmt.Println(err)
    } else {
        for _, g := range gists {
            fmt.Printf("%v\n\n", g.Files)
        }
    }
}

And I get the following output:

map[TODO.md:github.GistFile{Size:166, Filename:"TODO.md", RawURL:"somerawurlhere"}]

map[fourcore.c:github.GistFile{Size:309, Filename:"fourcore.c", RawURL:"somerawurlhere"}]

map[coretest.cpp:github.GistFile{Size:160, Filename:"coretest.cpp", RawURL:"somerawurlhere"}]

What I would like to print is "ID / FILENAME". I understand that I need to extract the ID from Gist type and Filename from above map but I wasn't able to find a way to do that. How do I do that? Help would be greatly appreciated.

PS: Here is the documentation describing Gist type.

You have Files map, where filename is stored in key variable of type GistFilename, and ID is in Gist type variable. So you have to have two range's - one for Gists, other for Files. Something like this:

    for _, g := range gists {
        for filename, _ := range g.Files {
            fmt.Printf("%v / %v\n", *g.ID, filename)
        }
    }

Full code:

package main

import (
    "code.google.com/p/goauth2/oauth"
    "fmt"
    "github.com/google/go-github/github"
)

func main() {
    t := &oauth.Transport{
        Token: &oauth.Token{AccessToken: "secretaccesstokenhere"},
    }

    client := github.NewClient(t.Client())

    gists, _, err := client.Gists.List("", nil)

    if err != nil {
        fmt.Println(err)
        return
    }
    for _, g := range gists {
        for filename, _ := range g.Files {
            fmt.Printf("%v / %v\n", *g.ID, filename)
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM