Skip to content

Instantly share code, notes, and snippets.

@rlynjb
Last active Aug 14, 2018
Embed
What would you like to do?
code sample for Google API oauth using GoLang
// Hello, hope you find this code useful
package main
import (
// this is a deprecated oauth lib from godoc.org
// i was going to use the new one (https://godoc.org/golang.org/x/oauth2/google)
// but due to a bug i've found and filed at github
// i decided to revert to the old one instead until the new one is stable
"code.google.com/p/goauth2/oauth/jwt"
"encoding/json"
"io/ioutil"
"net/http"
"os"
// optional, this is just a logger
log "github.com/Sirupsen/logrus"
)
// REQUIREMENTS: credentials for OAuth and HTTP Request
var (
// KEYS retrieved from Google Developer Console
// also add Service Email in Analytics as another user
gaServiceEmail = "xxxxxxxxxxxxxxxx@gaservice.coom"
// Private Key can be found inside JSON file downloaded from Dev Console
gaPrivateKey = []byte("<------ BEGIN HERE ------>...")
gaApiKey = "lkjf98hs--- SOME GIBBERISH KEY ---98hsdjif"
// Service: URLs can be found at
// https://developers.google.com/analytics/devguides/config/
// under Reference and Resources
// or refer to Google APIs Explorer inside Google Developer Console
gaScope string = "https://www.googleapis.com/auth/analytics"
gaAccountId string = "xxxxxx"
gaWebPropertyId string = "UA-xxxxxxx-x"
gaProfileId string = "xxxxxxx"
gaGoalsUrlRequest string = "https://www.googleapis.com/analytics/v3/management/accounts/" + gaAccountId + "/webproperties/" + gaWebPropertyId + "/profiles/" + gaProfileId + "/goals"
)
type Item struct {
Name string `json:"name"`
}
type GAReportData struct {
Kind string `json:"kind"`
Items []struct {
Item
} `json:"items"`
}
// README
// https://developers.google.com/accounts/docs/OAuth2ServiceAccount
// Explains OAuth2 Service Account flow and how code works
func getGAReportData() (err error) {
client := &http.Client{}
// Create JWT and jwt.NewToken does all the magic!
gaToken := jwt.NewToken(gaServiceEmail, gaScope, gaPrivateKey)
// Request access token to Google with client and JWT credentials
gaAccessToken, err := gaToken.Assert(client)
if err != nil {
log.Error("GA Report - Unable to request Access Token: ", err)
return
}
// Establish connection to the Service with access token
req, err := http.NewRequest("GET", gaGoalsUrlRequest+"?key="+gaApiKey, nil)
req.Header.Set("Authorization", "Bearer "+gaAccessToken.AccessToken)
resp, err := client.Do(req)
if err != nil {
log.Error("GA Report - Unable to establish connection: ", err)
return
}
defer resp.Body.Close()
// Read response data
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error("GA Report - Unable to read data: ", err)
return
}
// Decode data and get necessary data only
data := &GAReportData{}
err = json.Unmarshal(body, data)
if err != nil {
log.Error("GA Report - Unable to decode data: ", err)
return
}
// Encode data
// TODO
// use MarshalIndent to prettify for viewing/debugging purpose
// but use Marshal after
prettybody, _ := json.MarshalIndent(data, "", " ")
log.Debug("GA Report JSON: \n", string(prettybody))
return
}
// If you have any questions, please feel free to contact me, I'd be happy to assist you. :-)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment