Skip to content

Instantly share code, notes, and snippets.

@bemasher
Created October 26, 2012 23:10
Show Gist options
  • Save bemasher/3962095 to your computer and use it in GitHub Desktop.
Save bemasher/3962095 to your computer and use it in GitHub Desktop.
OAuth example creating an event using google's calendar api.
package main
import (
"os"
"fmt"
"time"
"net/http"
"errhandler"
"encoding/json"
"code.google.com/p/goauth2/oauth"
"code.google.com/p/google-api-go-client/calendar/v3"
)
const (
OAUTH_CONFIG = "client_secrets.json"
CACHE_FILE = "token.json"
CALENDAR_ID = "[email protected]"
)
var (
oauthConfig *oauth.Config
client *http.Client
)
type ClientSecrets struct {
Installed Installed `json:"installed"`
}
type Installed struct {
AuthProviderCertURL string `json:"auth_provider_x509_cert_url"`
AuthURI string `json:"auth_uri"`
ClientEmail string `json:"client_email"`
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
ClientCertURL string `json:"client_x509_cert_url"`
RedirectURIs []string `json:"redirect_uris"`
TokenURI string `json:"token_uri"`
}
func landingHandler(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, oauthConfig.AuthCodeURL(""), http.StatusFound)
}
func exchangeHandler(w http.ResponseWriter, r *http.Request) {
t := &oauth.Transport{Config: oauthConfig}
token, err := t.Exchange(r.FormValue("code"))
errhandler.Handle("Error exchanging for token: ", err)
c := oauth.CacheFile(CACHE_FILE)
err = c.PutToken(token)
errhandler.Handle("Error caching token: ", err)
os.Exit(0)
}
func init() {
// Read the client secrets
oauthConfigFile, err := os.Open(OAUTH_CONFIG)
errhandler.Handle("Error opening oauth oauthConfig: ", err)
defer oauthConfigFile.Close()
var clientSecrets ClientSecrets
oauthConfigDecoder := json.NewDecoder(oauthConfigFile)
err = oauthConfigDecoder.Decode(&clientSecrets)
errhandler.Handle("Error decoding oauth oauthConfig: ", err)
// Create a new oauth oauthConfiguration
oauthConfig = &oauth.Config{
ClientId: clientSecrets.Installed.ClientID,
ClientSecret: clientSecrets.Installed.ClientSecret,
Scope: "https://www.googleapis.com/auth/calendar",
AuthURL: clientSecrets.Installed.AuthURI,
TokenURL: clientSecrets.Installed.TokenURI,
RedirectURL: "http://localhost:8080/exchange",
AccessType: "offline",
}
// Try getting a token from cache
cache := oauth.CacheFile(CACHE_FILE)
token, err := cache.Token()
// If we failed we don't have any tokens so get one
if err != nil {
http.HandleFunc("/", landingHandler)
http.HandleFunc("/exchange", exchangeHandler)
fmt.Println("To authenticate visit: http://localhost:8080/")
http.ListenAndServe(":8080", nil)
}
// Create a new transport to refresh token if necessary
t := oauth.Transport{Config: oauthConfig, Token: token}
// If the token expired, refresh and cache it
if token.Expired() {
err := t.Refresh()
errhandler.Handle("Error refreshing token: ", err)
err = cache.PutToken(t.Token)
errhandler.Handle("Error caching token: ", err)
}
client = t.Client()
}
func main() {
calendarService, err := calendar.New(client)
errhandler.Handle("Error creating calendar service: ", err)
start := &calendar.EventDateTime{DateTime:time.Now().Format(time.RFC3339)}
fmt.Println(start)
end := &calendar.EventDateTime{DateTime:time.Now().Add(1 * time.Hour).Format(time.RFC3339)}
evt := &calendar.Event{Summary:"Test Event", Start:start, End:end}
e, err := calendarService.Events.Insert(CALENDAR_ID, evt).Do()
errhandler.Handle("Error creating event: ", err)
fmt.Printf("%+v\n", e)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment