Last active
February 5, 2019 07:49
-
-
Save mitsutaka/80c9824b52d026ba0409bcd1268d9552 to your computer and use it in GitHub Desktop.
GItHub Personal access token with http proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"errors" | |
"fmt" | |
"net" | |
"net/http" | |
"net/url" | |
"os" | |
"sort" | |
"strings" | |
"time" | |
"github.com/cybozu-go/log" | |
"github.com/google/go-github/v18/github" | |
version "github.com/hashicorp/go-version" | |
"golang.org/x/oauth2" | |
) | |
const token = "YOUR_TOKEN" | |
func main() { | |
u, err := url.Parse("http://localhost:3128") | |
if err != nil { | |
log.ErrorExit(err) | |
} | |
transport := &http.Transport{ | |
Proxy: http.ProxyURL(u), | |
DialContext: (&net.Dialer{ | |
Timeout: 30 * time.Second, | |
KeepAlive: 30 * time.Second, | |
DualStack: true, | |
}).DialContext, | |
MaxIdleConns: 100, | |
IdleConnTimeout: 90 * time.Second, | |
TLSHandshakeTimeout: 10 * time.Second, | |
ExpectContinueTimeout: 1 * time.Second, | |
} | |
proxyClient := &http.Client{ | |
Transport: transport, | |
Timeout: 1 * time.Hour, | |
} | |
ctx := context.Background() | |
// Set personal access token | |
ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: token}) | |
// Add proxyClient to oauth2.HTTPClient | |
ctx = context.WithValue(ctx, oauth2.HTTPClient, proxyClient) | |
// Create access token and proxy configuration included *http.Client | |
oc := oauth2.NewClient(ctx, ts) | |
client := github.NewClient(oc) | |
opt := &github.ListOptions{ | |
PerPage: 100, | |
} | |
var releases []*github.RepositoryRelease | |
for { | |
rs, resp, err := client.Repositories.ListReleases(ctx, "cybozu-go", "neco", opt) | |
if err != nil { | |
log.ErrorExit(err) | |
} | |
releases = append(releases, rs...) | |
if resp.NextPage == 0 { | |
break | |
} | |
opt.Page = resp.NextPage | |
} | |
versions := make([]*version.Version, 0, len(releases)) | |
for _, r := range releases { | |
if r.TagName == nil || r.GetDraft() { | |
continue | |
} | |
s := *r.TagName | |
trimmed := strings.SplitN(s, "-", 2) | |
// Ignore prefix in tag name. 'prefix-X.Y.Z' is formatted to 'X.Y.Z' | |
if len(trimmed) >= 2 { | |
s = trimmed[1] | |
} | |
v, err := version.NewVersion(s) | |
if err != nil { | |
continue | |
} | |
versions = append(versions, v) | |
} | |
sort.Sort(sort.Reverse(version.Collection(versions))) | |
if len(versions) == 0 { | |
log.ErrorExit(errors.New("no version")) | |
} | |
fmt.Println(versions) | |
os.Exit(0) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment