Skip to content

Instantly share code, notes, and snippets.

@jerryan999
Last active May 5, 2022 14:57
Show Gist options
  • Save jerryan999/3fa80271a165775af69fb793bc679e60 to your computer and use it in GitHub Desktop.
Save jerryan999/3fa80271a165775af69fb793bc679e60 to your computer and use it in GitHub Desktop.
context in Golang
ch := make(chan string, 1)
package main
import (
"context"
"fmt"
"time"
)
func main() {
// Channel used to receive the result from doSomething function
ch := make(chan string, 1)
// Create a context with a timeout of 5 seconds
ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
// Start the doSomething function
go doSomething(ctxTimeout, ch)
select {
case <-ctxTimeout.Done():
fmt.Printf("Context cancelled: %v\n", ctxTimeout.Err())
case result := <-ch:
fmt.Printf("Received: %s\n", result)
}
}
func doSomething(ctx context.Context, ch chan string) {
fmt.Println("doSomething Sleeping...")
time.Sleep(time.Second * 5)
fmt.Println("doSomething Wake up...")
ch <- "Did Something"
}
ctxTimeout, cancel := context.WithTimeout(context.Background(), time.Second*3)
defer cancel()
ctx, cancel := context.WithTimeout(context.Background(), time.Microsecond*200)
defer cancel()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, "https://google.com", nil)
if err != nil {
log.Fatalf("Error: %v", err)
return
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("Error: %v", err)
return
}
fmt.Println(resp.StatusCode)
opts := options.Client()
client, _ := mongo.Connect(context.TODO(), opts)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
client.Database("db").Collection("collection").InsertOne(ctx, bson.M{"x": 1})
func doSomething(ctx context.Context, ch chan string) {
fmt.Println("doSomething Sleeping...")
time.Sleep(time.Second * 5)
fmt.Println("doSomething Wake up...")
ch <- "Did Something"
}
go doSomething(ctxTimeout, ch)
select {
case <-ctxTimeout.Done():
fmt.Printf("Context cancelled: %v\n", ctxTimeout.Err())
case result := <-ch:
fmt.Printf("Received: %s\n", result)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment