Skip to content

Instantly share code, notes, and snippets.

@tailnode
Created December 31, 2017 02:04
Show Gist options
  • Save tailnode/83b9920a16f2ddf472bd7fd1643cabdc to your computer and use it in GitHub Desktop.
Save tailnode/83b9920a16f2ddf472bd7fd1643cabdc to your computer and use it in GitHub Desktop.
do with timeout in go
package main
import (
"errors"
"fmt"
"time"
)
var timeoutErr = errors.New("timeout")
func main() {
ret, err, f := genFunc()
if err := DoTimeout(f, 2*time.Second); err == timeoutErr {
fmt.Println("timeout")
return
}
fmt.Println("result", *ret, err)
}
// TODO change to time wheel
func DoTimeout(f func(), timeout time.Duration) error {
timer := time.NewTimer(timeout)
finish := make(chan struct{})
go func() {
f()
close(finish)
}()
select {
case <-finish:
timer.Stop()
return nil
case <-timer.C:
return timeoutErr
}
}
func query(t time.Duration) (int, error) {
time.Sleep(t)
return 11, errors.New("xx")
}
func genFunc() (*int, error, func()) {
var ret int
var err error
f := func() {
ret, err = query(time.Second)
}
return &ret, err, f
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment