Skip to content

Instantly share code, notes, and snippets.

@Sundrique
Created March 28, 2015 05:40
Show Gist options
  • Save Sundrique/105b9806db7eb7ca26a5 to your computer and use it in GitHub Desktop.
Save Sundrique/105b9806db7eb7ca26a5 to your computer and use it in GitHub Desktop.
Google Api
package main
import (
"html/template"
"log"
"net/http"
"code.google.com/p/google-api-go-client/youtube/v3"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
)
var notAuthenticatedTemplate = template.Must(template.ParseFiles("main.html"))
var userInfoTemplate = template.Must(template.ParseFiles("user.html"))
// variables used during oauth protocol flow of authentication
var (
code = ""
token = ""
)
var oauthCfg = &oauth2.Config{
ClientID: "869297951920-lishkp20se529676fmqmm9j2vfhq0bir.apps.googleusercontent.com",
ClientSecret: "JvF4PZHkN8dQAnO-IkGIqg-R",
RedirectURL: "http://localhost:8888/oauth2callback",
Scopes: []string{
"https://www.googleapis.com/auth/userinfo.profile",
youtube.YoutubeScope,
},
Endpoint: google.Endpoint,
}
const profileInfoURL = "https://www.googleapis.com/oauth2/v1/userinfo?alt=json"
func main() {
http.HandleFunc("/", handleRoot)
http.HandleFunc("/authorize", handleAuthorize)
//Google will redirect to this page to return your code, so handle it appropriately
http.HandleFunc("/oauth2callback", handleOAuth2Callback)
http.ListenAndServe(":8888", nil)
}
func handleRoot(w http.ResponseWriter, r *http.Request) {
notAuthenticatedTemplate.Execute(w, nil)
}
// Start the authorization process
func handleAuthorize(w http.ResponseWriter, r *http.Request) {
//Get the Google URL which shows the Authentication page to the user
url := oauthCfg.AuthCodeURL("")
//redirect user to that page
http.Redirect(w, r, url, http.StatusFound)
}
// Function that handles the callback from the Google server
func handleOAuth2Callback(w http.ResponseWriter, r *http.Request) {
//Get the code from the response
code := r.FormValue("code")
//t := &oauth.Transport{oauth.Config: oauthCfg}
// Exchange the received code for a token
tok, err := oauthCfg.Exchange(oauth2.NoContext, code)
if err != nil {
log.Fatal(err)
}
client := oauthCfg.Client(oauth2.NoContext, tok)
resp, _ := client.Get(profileInfoURL)
service, err := youtube.New(client)
if err != nil {
log.Fatalf("Error creating YouTube client: %v", err)
}
channel := &youtube.Channel{
//you channel details here
}
call := service.Channels.Update("invideoPromotion", channel)
channel, err = call.Do()
if err != nil {
log.Fatalf("Error updating YouTube channel: %v", err)
}
buf := make([]byte, 1024)
resp.Body.Read(buf)
userInfoTemplate.Execute(w, string(buf))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment