Skip to content

Instantly share code, notes, and snippets.

@quyen91
Created July 15, 2018 05:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save quyen91/75753068759a899a30cfc28bca762625 to your computer and use it in GitHub Desktop.
Save quyen91/75753068759a899a30cfc28bca762625 to your computer and use it in GitHub Desktop.
GO Demo - GitGo CLI
// "Package main" is the namespace declaration
// "main" is a keyword that tells GO that this project is intended to run as a binary/executable (as opposed to a Library)
package main
// importing standard libraries & third party library
import (
"fmt"
"os"
"strings"
// aliasing library names
flag "github.com/ogier/pflag"
)
// flags
var (
user string
)
// "main" is the entry point of our CLI app
func main() {
// parse flags
flag.Parse()
// if user does not supply flags, print usage
if flag.NFlag() == 0 {
printUsage()
}
// if multiple users are passed separated by commas, store them in a "users" array
users := strings.Split(user, ",")
fmt.Printf("Searching user(s): %s\n", users)
// "for... range" loop in GO allows us to iterate over each element of the array.
// "range" keyword can return the index of the element (e.g. 0, 1, 2, 3 ...etc)
// and it can return the actual value of the element.
// Since GO does not allow unused variables, we use the "_" character to tell GO we don't care about the index, but
// we want to get the actual user we're looping over to pass to the function.
for _, u := range users {
result := getUsers(u)
fmt.Println(`Username: `, result.Login)
fmt.Println(`Name: `, result.Name)
fmt.Println(`Email: `, result.Email)
fmt.Println(`Bio: `, result.Bio)
fmt.Println("")
}
}
// "init" is a special function. GO will execute the init() function before the main.
func init() {
// We pass the user variable we declared at the package level (above).
// The "&" character means we are passing the variable "by reference" (as opposed to "by value"),
// meaning: we don't want to pass a copy of the user variable. We want to pass the original variable.
flag.StringVarP(&user, "user", "u", "", "Search Users")
}
// printUsage is a custom function we created to print usage for our CLI app
func printUsage() {
fmt.Printf("Usage: %s [options]\n", os.Args[0])
fmt.Println("Options:")
flag.PrintDefaults()
os.Exit(1)
}
// "Package main" is the namespace declaration
package main
// importing standard libraries
import (
"encoding/json"
"time"
"io/ioutil"
"log"
"net/http"
)
// constants
const (
apiURL = "https://api.github.com"
userEndpoint = "/users/"
)
// User struct represents the JSON data from GitHub API: https://api.github.com/users/defunct
// This struct was generated via a JSON-to-GO utility by Matt Holt: https://mholt.github.io/json-to-go/
type User struct {
Login string `json:"login"`
ID int `json:"id"`
AvatarURL string `json:"avatar_url"`
GravatarID string `json:"gravatar_id"`
URL string `json:"url"`
HTMLURL string `json:"html_url"`
FollowersURL string `json:"followers_url"`
FollowingURL string `json:"following_url"`
GistsURL string `json:"gists_url"`
StarredURL string `json:"starred_url"`
SubscriptionsURL string `json:"subscriptions_url"`
OrganizationsURL string `json:"organizations_url"`
ReposURL string `json:"repos_url"`
EventsURL string `json:"events_url"`
ReceivedEventsURL string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
Name string `json:"name"`
Company string `json:"company"`
Blog string `json:"blog"`
Location string `json:"location"`
Email string `json:"email"`
Hireable interface{} `json:"hireable"`
Bio string `json:"bio"`
PublicRepos int `json:"public_repos"`
PublicGists int `json:"public_gists"`
Followers int `json:"followers"`
Following int `json:"following"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// getUsers queries GitHub API for a given user
func getUsers(name string) User {
// send GET request to GitHub API with the requested user "name"
resp, err := http.Get(apiURL + userEndpoint + name)
// if err occurs during GET request, then throw error and quit application
if err != nil {
log.Fatalf("Error retrieving data: %s\n", err)
}
// Always good practice to defer closing the response body.
// If application crashes or function finishes successfully, GO will always execute this "defer" statement
defer resp.Body.Close()
// read the response body and handle any errors during reading.
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalf("Error reading data: %s\n", err)
}
// create a user variable of type "User" struct to store the "Unmarshal"-ed (aka parsed JSON) data, then return the user
var user User
json.Unmarshal(body, &user)
return user
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment