Search code examples
gogoogle-calendar-apiservice-accounts

Display google calendar events authenticating as service account - Golang App


Within my Go app, currently running as localhost on my dev machine (ultimately on a Linode), I wish to simply display public Google Calendar events from a calendar in my own Google account. At the moment this only displays to console because I want to get it working in principle and I have this code in the index page handler of my app.

googleCalendar, err := calendar.NewService(r.Context(), option.WithCredentialsFile("./googleAuth.json"))
    if err != nil {
        app.errorLog.Println(w, err)
    }
    
    calEvents, err := googleCalendar.Events.List("primary").TimeMin(time.Now().Format(time.RFC3339)).MaxResults(5).Do()
    if err != nil {
        app.errorLog.Println(err)
    }
    
    if len(calEvents.Items) > 0 {
        for _, i := range calEvents.Items {
            fmt.Fprintln(w, i.Summary, " ", i.Start.DateTime)
        }
    } else {
        app.errorLog.Println("No calendar events to display")
    }

The only way I think to do this is to use a service account because I am not a G Workspace (GSuite) user (the app will finally run on a Linode), Oauth2 directly is overkill and likely not available in my circumstances anyhow. I have enabled Google calendar API in my Google Dev Console and setup a service account, created / downloaded a json key file (as in the code). I have added the service account email as a shared user to the necessary calendar. The code compiles and runs but I only get my "No calendar events to display" because 'Items' is empty (the calendar does have events). Is there more here that needs to be done ? How to fetch these calendar event ? thanks


Solution

  • Well, I finally found a solution to this issue. The code I posted is all that's needed in this case BUT it's the use of the keyword "primary" which is not working. I do not know why, it should work according to the Google documentation. I simply substituted "primary" with the actual calendar ID (not the calendar name) and all my events displayed. 🙄