Comprehensive Lesson Plan: Building a Real-Time Chat Collaboration Tool with Golang and Google Sheets API
This Lab Workbook provides a comprehensive and in-depth learning experience for students. It includes:
A more detailed introduction to the project and technology stack.
Step-by-step instructions for setting up the Google Cloud environment, including how to obtain the necessary IDs and credentials.
An expanded code example with more features, such as reading recent messages and a simple chat interface.
Additional sections on understanding the code, testing, and debugging.
Suggestions for extending the project and homework assignments.
Comprehensive Lesson Plan: Building a Real-Time Chat Collaboration Tool with Golang and Google Sheets API
## Overview
Learning outcomes:
Guides students through creating a sophisticated real-time chat collaboration tool using Golang and the Google Sheets API.
By the end of this lesson, students will have hands-on experience with:
Go programming
RESTful API interactions
OAuth2 authentication
practical application of Google Cloud services.
## Learning Objectives
By the end of this lesson, students will be able to:
1. Set up a Google Cloud project and enable necessary APIs
2. Implement OAuth2 authentication for Google services
3. Use Golang to interact with the Google Sheets API
4. Create a functional real-time chat application
5. Understand the principles of API-based application development
## Learning Topics we will study in this Lab:
- Basic knowledge of Go programming
- Familiarity with RESTful APIs
- Google Cloud account
- Go (1.16+) installed on local machine
## Duration
180 minutes (3 hours)
## Materials
- Computers with Go installed
- Internet connection
- Google Cloud account
- Visual Studio Code or any preferred code editor
## Lesson Structure
### 1. Introduction to the Project (20 minutes)
#### 1.1 Project Overview
- Introduce the concept of a real-time chat collaboration tool
- Explain the architecture: Golang backend + Google Sheets as a simple database
- Discuss real-world applications of such tools in education and business
1.2 Technology Stack Introduction
- Go (Golang): Brief overview of its strengths in building concurrent applications
- Google Sheets API: Explain its role as a simple, accessible database
- OAuth2: Discuss its importance in secure API authentication
### 2. Setting Up the Development Environment (30 minutes)
#### 2.1 Google Cloud Setup
1. Create a new Google Cloud Project:
- Go to [Google Cloud Console](https://console.cloud.google.com/)
- Click on the project dropdown > New Project
- Name your project (e.g., "GoChat Collaborator") and create
2. Enable Google Sheets API:
- In the Cloud Console, go to "APIs & Services" > "Library"
- Search for "Google Sheets API" and enable it
*** 3. Create OAuth 2.0 Credentials:
- Go to "APIs & Services" > "Credentials"
- Click "Create Credentials" > "OAuth client ID"
- Choose "Desktop app" as the application type
- Download the JSON file and rename it to `credentials.json`
#### 2.2 Go Environment Setup
1. Install necessary Go packages:
```bash
go get -u google.golang.org/api/sheets/v4
go get -u golang.org/x/oauth2
go get -u golang.org/x/oauth2/google
```
2. Create a new directory for your project:
```bash
mkdir gochat-collaborator
cd gochat-collaborator
```
3. Initialize Go module:
```bash
go mod init gochat-collaborator
```
4. Place the `credentials.json` file in this directory
### 3. Building the Application (90 minutes)
#### 3.1 Creating the Google Sheet
1. Go to [Google Sheets](https://sheets.google.com)
2. Create a new spreadsheet and name it "GoChat Collaborator"
3. Note the spreadsheet ID from the URL:
- URL format: `https://docs.google.com/spreadsheets/d/[SPREADSHEET_ID]/edit#gid=0`
- The [SPREADSHEET_ID] is what you need
#### 3.2 Writing the Go Application
Create a file named `main.go` and implement the following features:
1. OAuth2 Authentication
2. Connecting to Google Sheets API
3. Writing messages to the sheet
4. Reading messages from the sheet
Here's the enhanced code with comments explaining each section:
const (
// Update this with your Google Sheet ID
spreadsheetID = "YOUR_SPREADSHEET_ID_HERE"
// The range where we'll write and read messages
messageRange = "Sheet1!A:B"
)
// Save token to file
func saveToken(path string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", path)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}
// Get client using credentials
func getClient(config *oauth2.Config) *http.Client {
tokFile := "token.json"
tok, err := tokenFromFile(tokFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokFile, tok)
}
return config.Client(context.Background(), tok)
}
// Retrieve token from web for first-time use
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
log.Fatalf("Unable to read authorization code: %v", err)
}
tok, err := config.Exchange(context.TODO(), authCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return tok
}
// Configure the OAuth2 client
config, err := google.ConfigFromJSON(b, sheets.SpreadsheetsScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(config)
// Create a Sheets service
srv, err := sheets.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Unable to retrieve Sheets client: %v", err)
}
// Main chat loop
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter your message (or 'quit' to exit): ")
scanner.Scan()
message := scanner.Text()
if message == "quit" {
break
}
// Append the message to the sheet
timestamp := time.Now().Format(time.RFC3339)
values := [][]interface{}{{timestamp, message}}
valueRange := &sheets.ValueRange{
Values: values,
}
_, err = srv.Spreadsheets.Values.Append(spreadsheetID, messageRange, valueRange).
ValueInputOption("USER_ENTERED").Do()
if err != nil {
log.Printf("Unable to append data to sheet: %v", err)
continue
}
fmt.Println("Message sent successfully!")
// Read and display the last 5 messages
resp, err := srv.Spreadsheets.Values.Get(spreadsheetID, messageRange).Do()
if err != nil {
log.Printf("Unable to retrieve data from sheet: %v", err)
continue
}
fmt.Println("\nLast 5 messages:")
start := len(resp.Values) - 5
if start < 0 {
start = 0
}
for i := start; i < len(resp.Values); i++ {
row := resp.Values[i]
fmt.Printf("%s: %s\n", row[0], row[1])
}
fmt.Println()
}
}
```
#### 3.3 Running the Application
1. Replace `YOUR_SPREADSHEET_ID_HERE` with your actual Google Sheet ID
2. Run the application:
```bash
go run main.go
```
3. Follow the OAuth2 authentication process when prompted
4. Start chatting and observe the messages being written to and read from the Google Sheet
### 4. Understanding the Code (30 minutes)
Break down the code and explain key concepts:
- OAuth2 flow and token management
- Google Sheets API interactions (reading and writing)
- Goroutines and channels for concurrent operations (if implemented)
- Error handling and logging
### 5. Testing and Debugging (20 minutes)
Guide students through:
- Common errors and their solutions
- Using Go's built-in testing framework
- Debugging techniques specific to API-based applications
### 6. Extension and Homework (10 minutes)
Suggest ways to extend the project:
1. Implement user authentication
2. Add support for multiple chat rooms (different sheets)
3. Create a simple web interface using a Go web framework like Gin or Echo
4. Implement real-time updates using websockets
## Assessment
- Participation in building and running the app
- Code review of the completed chat application
- Homework assignment: Implement one of the suggested extensions
## Additional Resources
- [Go Documentation](https://golang.org/doc/)
- [Google Sheets API Documentation](https://developers.google.com/sheets/api)
- [OAuth 2.0 for Mobile & Desktop Apps](https://developers.google.com/identity/protocols/oauth2/native-app)
This comprehensive lesson plan provides a deep dive into creating a functional chat application using Go and Google Sheets, offering students valuable experience with real-world API integration and OAuth2 authentication.
This enhanced lesson plan provides a more comprehensive and in-depth learning experience for students. It includes:
1. A more detailed introduction to the project and technology stack.
2. Step-by-step instructions for setting up the Google Cloud environment, including how to obtain the necessary IDs and credentials.
3. An expanded code example with more features, such as reading recent messages and a simple chat interface.
4. Additional sections on understanding the code, testing, and debugging.
5. Suggestions for extending the project and homework assignments.
6. A list of additional resources for further learning.
This structure allows for a more thorough exploration of the concepts and provides students with a more robust foundation for building real-world applications using Go and Google APIs. The lesson now covers not just the basics of API interaction, but also touches on important software development practices like error handling, testing, and project extension.
## Overview
This advanced lesson plan guides students through creating a sophisticated real-time chat collaboration tool using Golang and the Google Sheets API. By the end of this lesson, students will have hands-on experience with Go programming, RESTful API interactions, OAuth2 authentication, and practical application of Google Cloud services.
## Learning Objectives
By the end of this lesson, students will be able to:
1. Set up a Google Cloud project and enable necessary APIs
2. Implement OAuth2 authentication for Google services
3. Use Golang to interact with the Google Sheets API
4. Create a functional real-time chat application
5. Understand the principles of API-based application development
## Prerequisites
- Basic knowledge of Go programming
- Familiarity with RESTful APIs
- Google Cloud account
- Go (1.16+) installed on local machine
## Duration
180 minutes (3 hours)
## Materials
- Computers with Go installed
- Internet connection
- Google Cloud account
- Visual Studio Code or any preferred code editor
## Lesson Structure
### 1. Introduction to the Project (20 minutes)
#### 1.1 Project Overview
- Introduce the concept of a real-time chat collaboration tool
- Explain the architecture: Golang backend + Google Sheets as a simple database
- Discuss real-world applications of such tools in education and business
#### 1.2 Technology Stack Introduction
- Go (Golang): Brief overview of its strengths in building concurrent applications
- Google Sheets API: Explain its role as a simple, accessible database
- OAuth2: Discuss its importance in secure API authentication
### 2. Setting Up the Development Environment (30 minutes)
#### 2.1 Google Cloud Setup
1. Create a new Google Cloud Project:
- Go to [Google Cloud Console](https://console.cloud.google.com/)
- Click on the project dropdown > New Project
- Name your project (e.g., "GoChat Collaborator") and create
2. Enable Google Sheets API:
- In the Cloud Console, go to "APIs & Services" > "Library"
- Search for "Google Sheets API" and enable it
3. Create OAuth 2.0 Credentials:
- Go to "APIs & Services" > "Credentials"
- Click "Create Credentials" > "OAuth client ID"
- Choose "Desktop app" as the application type
- Download the JSON file and rename it to `credentials.json`
#### 2.2 Go Environment Setup
1. Install necessary Go packages:
```bash
go get -u google.golang.org/api/sheets/v4
go get -u golang.org/x/oauth2
go get -u golang.org/x/oauth2/google
```
2. Create a new directory for your project:
```bash
mkdir gochat-collaborator
cd gochat-collaborator
```
3. Initialize Go module:
```bash
go mod init gochat-collaborator
```
4. Place the `credentials.json` file in this directory
### 3. Building the Application (90 minutes)
#### 3.1 Creating the Google Sheet
1. Go to [Google Sheets](https://sheets.google.com)
2. Create a new spreadsheet and name it "GoChat Collaborator"
3. Note the spreadsheet ID from the URL:
- URL format: `https://docs.google.com/spreadsheets/d/[SPREADSHEET_ID]/edit#gid=0`
- The [SPREADSHEET_ID] is what you need
#### 3.2 Writing the Go Application
Create a file named `main.go` and implement the following features:
1. OAuth2 Authentication
2. Connecting to Google Sheets API
3. Writing messages to the sheet
4. Reading messages from the sheet
Here's the enhanced code with comments explaining each section:
const (
// Update this with your Google Sheet ID
spreadsheetID = "YOUR_SPREADSHEET_ID_HERE"
// The range where we'll write and read messages
messageRange = "Sheet1!A:B"
)
// Save token to file
func saveToken(path string, token *oauth2.Token) {
fmt.Printf("Saving credential file to: %s\n", path)
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatalf("Unable to cache oauth token: %v", err)
}
defer f.Close()
json.NewEncoder(f).Encode(token)
}
// Get client using credentials
func getClient(config *oauth2.Config) *http.Client {
tokFile := "token.json"
tok, err := tokenFromFile(tokFile)
if err != nil {
tok = getTokenFromWeb(config)
saveToken(tokFile, tok)
}
return config.Client(context.Background(), tok)
}
// Retrieve token from web for first-time use
func getTokenFromWeb(config *oauth2.Config) *oauth2.Token {
authURL := config.AuthCodeURL("state-token", oauth2.AccessTypeOffline)
fmt.Printf("Go to the following link in your browser then type the "+
"authorization code: \n%v\n", authURL)
var authCode string
if _, err := fmt.Scan(&authCode); err != nil {
log.Fatalf("Unable to read authorization code: %v", err)
}
tok, err := config.Exchange(context.TODO(), authCode)
if err != nil {
log.Fatalf("Unable to retrieve token from web: %v", err)
}
return tok
}
// Configure the OAuth2 client
config, err := google.ConfigFromJSON(b, sheets.SpreadsheetsScope)
if err != nil {
log.Fatalf("Unable to parse client secret file to config: %v", err)
}
client := getClient(config)
// Create a Sheets service
srv, err := sheets.NewService(ctx, option.WithHTTPClient(client))
if err != nil {
log.Fatalf("Unable to retrieve Sheets client: %v", err)
}
// Main chat loop
scanner := bufio.NewScanner(os.Stdin)
for {
fmt.Print("Enter your message (or 'quit' to exit): ")
scanner.Scan()
message := scanner.Text()
if message == "quit" {
break
}
// Append the message to the sheet
timestamp := time.Now().Format(time.RFC3339)
values := [][]interface{}{{timestamp, message}}
valueRange := &sheets.ValueRange{
Values: values,
}
_, err = srv.Spreadsheets.Values.Append(spreadsheetID, messageRange, valueRange).
ValueInputOption("USER_ENTERED").Do()
if err != nil {
log.Printf("Unable to append data to sheet: %v", err)
continue
}
fmt.Println("Message sent successfully!")
// Read and display the last 5 messages
resp, err := srv.Spreadsheets.Values.Get(spreadsheetID, messageRange).Do()
if err != nil {
log.Printf("Unable to retrieve data from sheet: %v", err)
continue
}
fmt.Println("\nLast 5 messages:")
start := len(resp.Values) - 5
if start < 0 {
start = 0
}
for i := start; i < len(resp.Values); i++ {
row := resp.Values[i]
fmt.Printf("%s: %s\n", row[0], row[1])
}
fmt.Println()
}
}
```
#### 3.3 Running the Application
1. Replace `YOUR_SPREADSHEET_ID_HERE` with your actual Google Sheet ID
2. Run the application:
```bash
go run main.go
```
3. Follow the OAuth2 authentication process when prompted
4. Start chatting and observe the messages being written to and read from the Google Sheet
### 4. Understanding the Code (30 minutes)
Break down the code and explain key concepts:
- OAuth2 flow and token management
- Google Sheets API interactions (reading and writing)
- Goroutines and channels for concurrent operations (if implemented)
- Error handling and logging
### 5. Testing and Debugging (20 minutes)
Guide students through:
- Common errors and their solutions
- Using Go's built-in testing framework
- Debugging techniques specific to API-based applications
### 6. Extension and Homework (10 minutes)
Suggest ways to extend the project:
1. Implement user authentication
2. Add support for multiple chat rooms (different sheets)
3. Create a simple web interface using a Go web framework like Gin or Echo
4. Implement real-time updates using websockets
## Assessment
- Participation in building and running the app
- Code review of the completed chat application
- Homework assignment: Implement one of the suggested extensions
## Additional Resources
- [Go Documentation](https://golang.org/doc/)
- [Google Sheets API Documentation](https://developers.google.com/sheets/api)
- [OAuth 2.0 for Mobile & Desktop Apps](https://developers.google.com/identity/protocols/oauth2/native-app)
This comprehensive lesson plan provides a deep dive into creating a functional chat application using Go and Google Sheets, offering students valuable experience with real-world API integration and OAuth2 authentication.
Want to print your doc? This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (