Created
July 25, 2019 09:30
-
-
Save tiagotele/b81b4d8765a9ee4cc9d39b2575cf649f to your computer and use it in GitHub Desktop.
Getting started with github API
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
// Copyright 2015 The go-github AUTHORS. All rights reserved. | |
// | |
// Use of this source code is governed by a BSD-style | |
// license that can be found in the LICENSE file. | |
// The basicauth command demonstrates using the github.BasicAuthTransport, | |
// including handling two-factor authentication. This won't currently work for | |
// accounts that use SMS to receive one-time passwords. | |
package main | |
import ( | |
"bufio" | |
"context" | |
"fmt" | |
"os" | |
"strings" | |
"syscall" | |
"flag" | |
"log" | |
"github.com/google/go-github/github" | |
"golang.org/x/crypto/ssh/terminal" | |
) | |
var ( | |
name = flag.String("name", "Testing client", "Name of repo to create in authenticated user's GitHub account.") | |
description = flag.String("description", "If someone see this on github thats a good sign...", "Description of created repo.") | |
private = flag.Bool("private", false, "Will created repo be private.") | |
) | |
func main() { | |
r := bufio.NewReader(os.Stdin) | |
fmt.Print("GitHub Username: ") | |
username, _ := r.ReadString('\n') | |
fmt.Print("GitHub Password: ") | |
bytePassword, _ := terminal.ReadPassword(int(syscall.Stdin)) | |
password := string(bytePassword) | |
tp := github.BasicAuthTransport{ | |
Username: strings.TrimSpace(username), | |
Password: strings.TrimSpace(password), | |
} | |
client := github.NewClient(tp.Client()) | |
ctx := context.Background() | |
user, _, err := client.Users.Get(ctx, "") | |
// Is this a two-factor auth error? If so, prompt for OTP and try again. | |
if _, ok := err.(*github.TwoFactorAuthError); ok { | |
fmt.Print("\nGitHub OTP: ") | |
otp, _ := r.ReadString('\n') | |
tp.OTP = strings.TrimSpace(otp) | |
user, _, err = client.Users.Get(ctx, "") | |
} | |
if err != nil { | |
fmt.Printf("\nerror: %v\n", err) | |
return | |
} | |
fmt.Printf("\n%v\n", github.Stringify(user)) | |
flag.Parse() | |
repository := &github.Repository{Name: name, Private: private, Description: description} | |
repo, _, err := client.Repositories.Create(ctx, "", repository) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Printf("Successfully created new repo: %v\n", repo.GetName()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment