Skip to content

Instantly share code, notes, and snippets.

@sundy-li
Last active May 7, 2017 11:05
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 sundy-li/d41657cd89ba747c0c86c12bb2a85c04 to your computer and use it in GitHub Desktop.
Save sundy-li/d41657cd89ba747c0c86c12bb2a85c04 to your computer and use it in GitHub Desktop.
golang-context
package gomarker
type service func() result
func invokeService(ctx content.Content, s service) chan result {
c := make(chan result)
go func() {
c1 := make(chan result)
go func() {
c1 <- s()
}()
select {
case v := <-c1:
c <- v
case <-ctx.Done():
// cancel this in-flight request by closing its connection.
}
}()
return c
}
func handleRequestByDAM() {
ctx, cf := context.WithCancel(context.Background())
c1, c2, c3 := invokeService(ctx, service1), invokeService(ctx, service2),
invokeService(ctx, service3)
timeout := time.After(200 * time.Millisecond)
for {
select {
case r := <-c1:
//handle result1
case r := <-c2:
//handle result2
case r := <-c3:
//handle result3
case <-timeout:
cf() // cancel all service invoke requests
return
}
}
return
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment