File: timeout.go

package info (click to toggle)
golang-github-evilsocket-islazy 1.11.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 292 kB
  • sloc: javascript: 8; makefile: 3
file content (30 lines) | stat: -rw-r--r-- 618 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package async

import (
	"time"
)

// TimedCallback represents a generic function with a return value.
type TimedCallback func() interface{}

// WithTimeout will execute the callback and return its value or a
// ErrTimeout if its execution will exceed the provided duration.
func WithTimeout(tm time.Duration, cb TimedCallback) (interface{}, error) {
	timeout := time.After(tm)
	done := make(chan interface{})
	go func() {
		done <- cb()
	}()

	select {
	case <-timeout:
		return nil, ErrTimeout
	case res := <-done:
		if res != nil {
			if e, ok := res.(error); ok {
				return nil, e
			}
		}
		return res, nil
	}
}