forked from RichardKnop/machinery
-
Notifications
You must be signed in to change notification settings - Fork 0
/
validate.go
42 lines (35 loc) · 1.08 KB
/
validate.go
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
31
32
33
34
35
36
37
38
39
40
41
42
package tasks
import (
"errors"
"reflect"
)
var (
// ErrTaskMustBeFunc ...
ErrTaskMustBeFunc = errors.New("Task must be a func type")
// ErrTaskReturnsNoValue ...
ErrTaskReturnsNoValue = errors.New("Taks must return at least a single value")
// ErrLastReturnValueMustBeError ..
ErrLastReturnValueMustBeError = errors.New("Last return value of a task must be error")
)
// ValidateTask validates task function using reflection and makes sure
// it has a proper signature. Functions used as tasks must return at least a
// single value and the last return type must be error
func ValidateTask(task interface{}) error {
v := reflect.ValueOf(task)
t := v.Type()
// Task must be a function
if t.Kind() != reflect.Func {
return ErrTaskMustBeFunc
}
// Task must return at least a single value
if t.NumOut() < 1 {
return ErrTaskReturnsNoValue
}
// Last return value must be error
lastReturnType := t.Out(t.NumOut() - 1)
errorInterface := reflect.TypeOf((*error)(nil)).Elem()
if !lastReturnType.Implements(errorInterface) {
return ErrLastReturnValueMustBeError
}
return nil
}