Last active
September 24, 2023 12:44
-
-
Save stvoidit/fb8954ce607c29aa1365abbe193526dc to your computer and use it in GitHub Desktop.
use golang context
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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