Skip to content

Instantly share code, notes, and snippets.

@stvoidit
Last active September 24, 2023 12:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stvoidit/fb8954ce607c29aa1365abbe193526dc to your computer and use it in GitHub Desktop.
Save stvoidit/fb8954ce607c29aa1365abbe193526dc to your computer and use it in GitHub Desktop.
use golang context
package main
import (
"context"
"errors"
"fmt"
"time"
)
func main() {
ctx, cancel := context.WithTimeout(context.Background(), time.Millisecond*1500)
defer cancel()
for i := 1; i <= 10; i++ {
response := ctxFetch(ctx, i)
fmt.Printf("%+v is ctx.cancel: %v\n", response, errors.Is(response.Err, context.DeadlineExceeded))
}
time.Sleep(time.Second * 5)
}
type Response struct {
Data any
Code int
Err error
}
func ctxFetch(ctx context.Context, id any) Response {
res := make(chan Response)
go func() {
defer close(res)
res <- fetch(id)
}()
select {
case <-ctx.Done():
return Response{Data: id, Code: 415, Err: fmt.Errorf("cancel: %w", ctx.Err())}
case response := <-res:
return response
}
}
func fetch(id any) Response {
time.Sleep(time.Millisecond * 500)
return Response{
Data: id,
Code: 200,
Err: nil,
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment