Skip to content

Instantly share code, notes, and snippets.

@iampato
Created May 5, 2023 16:15
Show Gist options
  • Save iampato/3635a1f41f363f925654d75e288c41a4 to your computer and use it in GitHub Desktop.
Save iampato/3635a1f41f363f925654d75e288c41a4 to your computer and use it in GitHub Desktop.
To watch and observe a Google Sheet in GoLang, you can use the Google Sheets API to access the sheet and the time package to set up a timer to check for changes periodically. Here's an example code snippet that demonstrates this:
package main
import (
"context"
"fmt"
"log"
"time"
"google.golang.org/api/sheets/v4"
"google.golang.org/api/option"
)
func main() {
// Set up the Google Sheets API client.
ctx := context.Background()
creds, err := google.FindDefaultCredentials(ctx, sheets.Scope)
if err != nil {
log.Fatalf("Unable to retrieve credentials: %v", err)
}
client, err := google.DefaultClient(ctx, sheets.Scope, option.WithCredentials(creds))
if err != nil {
log.Fatalf("Unable to create Google Sheets API client: %v", err)
}
sheetsService, err := sheets.New(client)
if err != nil {
log.Fatalf("Unable to create Google Sheets API service: %v", err)
}
// Specify the spreadsheet ID and sheet range.
spreadsheetID := "<your spreadsheet ID>"
sheetRange := "<your sheet name>"
// Set up a timer to check for changes every 5 seconds.
ticker := time.NewTicker(5 * time.Second)
defer ticker.Stop()
// Loop indefinitely to watch for changes.
for {
select {
case <-ticker.C:
// Call the Google Sheets API to get the latest data from the sheet.
resp, err := sheetsService.Spreadsheets.Values.Get(spreadsheetID, sheetRange).Do()
if err != nil {
log.Fatalf("Unable to retrieve data from sheet: %v", err)
}
// Print the data to the console.
fmt.Printf("Data: %v\n", resp.Values)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment