package main
import (
"context"
"errors"
"fmt"
"time"
)
type result struct {
record string
err error
}
func search(term string) (string, error) {
time.Sleep(200 * time.Millisecond)
return "some value", nil
}
func process(term string) error {
ctx, cancel := context.WithTimeout(context.Background(), 100 * time.Millisecond)
defer cancel()
// 此处使用容量为1的chan是为了防止goroutine泄露
ch := make(chan result, 1)
go func() {
record, err := search(term)
ch <- result{record: record, err: err}
}()
select {
case <- ctx.Done():
return errors.New("search canceled")
case result := <- ch:
if result.err != nil {
return result.err
}
fmt.Println("record:", result.record)
return nil
}
}