Skip to content

Instantly share code, notes, and snippets.

@y-abe
Created March 1, 2016 02:17
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 y-abe/547f0e281b180af6ae4b to your computer and use it in GitHub Desktop.
Save y-abe/547f0e281b180af6ae4b to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"time"
"golang.org/x/net/context"
)
func leafFunc(ctx context.Context) string {
ch := make(chan string)
go func() {
time.Sleep(time.Second * 2) // 2秒でhelloが返る
ch <- "hello"
}()
select {
case <-ctx.Done(): // 途中でキャンセルできる
return "done"
case resp := <-ch:
return resp
}
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
cancel()
resp := leafFunc(ctx)
fmt.Println(resp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment