Skip to content

Instantly share code, notes, and snippets.

@IndianGuru
Created April 13, 2015 04:40
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 IndianGuru/2f686c755b4ec4cf67bb to your computer and use it in GitHub Desktop.
Save IndianGuru/2f686c755b4ec4cf67bb to your computer and use it in GitHub Desktop.
Accessing GitHub using Golang
package main
import (
"fmt"
"net/http"
"github.com/google/go-github/github"
"golang.org/x/oauth2"
githuboauth "golang.org/x/oauth2/github"
"html/template"
)
var (
// You must register the app at https://github.com/settings/applications
// Set callback to http://127.0.0.1:7000/githuboa_cb
// Set ClientId and ClientSecret to the values you got
// after registering your app
oauthConf = &oauth2.Config{
ClientID: "00dd2026980943db89e3",
ClientSecret: "199a2a05e29f30c547e1525c549bf89d3bdbc51c",
// select level of access you want https://developer.github.com/v3/oauth/#scopes
Scopes: []string{"user:email"},
// Endpoint contains the resource server's token endpoint
// URLs. These are constants specific to each server and are
// often available via site-specific packages, such as
// google.Endpoint or github.Endpoint.
Endpoint: githuboauth.Endpoint,
}
// An unguessable random string. It is used to protect against
// cross-site request forgery attacks
oauthStateString = "arandomstring"
)
const htmlIndex = `<html><body><p>Well, hello there!</p>
<p>We're going to now talk to the GitHub API. Ready?</p>
<p>Log into <a href="/login">GitHub</a></p>
</body></html>
`
var userInfoTemplate = template.Must(template.New("").Parse(`
<html><body>
<p>This app is now authenticated to access your GitHub user info.</p>
<p>User details are:</p><p>
{{.}}
</p>
<p>That's it!</p>
</body></html>
`))
func main() {
http.HandleFunc("/", handleMain)
http.HandleFunc("/login", handleGitHubLogin)
http.HandleFunc("/githuboa_cb", handleGitHubCallback)
fmt.Print("Started running on http://127.0.0.1:7000\n")
fmt.Println(http.ListenAndServe(":7000", nil))
}
func handleMain(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusOK)
w.Write([]byte(htmlIndex))
}
// /login
func handleGitHubLogin(w http.ResponseWriter, r *http.Request) {
url := oauthConf.AuthCodeURL(oauthStateString, oauth2.AccessTypeOnline)
http.Redirect(w, r, url, http.StatusTemporaryRedirect)
}
// githuboa_cb. Called by github after authorization is granted
func handleGitHubCallback(w http.ResponseWriter, r *http.Request) {
// If the user accepts your request, GitHub redirects back
// to your site with a temporary code in a code parameter
// as well as the state you provided in the previous step
// in a state parameter. If the states don't match, the
// request has been created by a third party and the process
// should be aborted.
state := r.FormValue("state")
if state != oauthStateString {
fmt.Printf("invalid oauth state, expected '%s', got '%s'\n", oauthStateString, state)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
code := r.FormValue("code")
// On success, exchange this for an access token
token, err := oauthConf.Exchange(oauth2.NoContext, code)
if err != nil {
fmt.Printf("oauthConf.Exchange() failed with '%s'\n", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
oauthClient := oauthConf.Client(oauth2.NoContext, token)
// https://godoc.org/github.com/google/go-github/github
client := github.NewClient(oauthClient)
user, _, err := client.Users.Get("")
if err != nil {
fmt.Printf("client.Users.Get() failed with '%s'\n", err)
http.Redirect(w, r, "/", http.StatusTemporaryRedirect)
return
}
buf := []string{"GitHub login id: ", *user.Login, "| GitHub email id: ", *user.Email}
userInfoTemplate.Execute(w, buf)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment