-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathjob.go
78 lines (61 loc) · 1.58 KB
/
job.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package asyncexecutor
import (
"errors"
"reflect"
)
type parameterObject struct {
parameters []interface{}
}
type ResponseObject struct {
ID int
Responses []interface{}
}
type CallableJob interface {
call() *ResponseObject
}
type callableType interface{}
type Job struct {
id int
paramObj *parameterObject
response *ResponseObject
responseChannel chan *ResponseObject
callable callableType
}
func NewJob(id int, function callableType, paramObject *parameterObject) (*Job, error) {
if function == nil {
return nil, errors.New("Callable cannot be nil")
}
funcV := reflect.ValueOf(function)
if funcV.Kind() != reflect.Func {
return nil, errors.New("Callable argument must be a function")
}
return &Job{
id,
paramObject,
new(ResponseObject),
make(chan *ResponseObject, 1),
function,
}, nil
}
func (job *Job) Await() *ResponseObject {
return <-job.responseChannel
}
func (job *Job) call() *ResponseObject {
reflectedParams := reflect.TypeOf(job.callable)
reflectedFunc := reflect.ValueOf(job.callable)
params := make([]reflect.Value, reflectedParams.NumIn())
for i := 0; i < reflectedParams.NumIn(); i++ {
params[i] = reflect.ValueOf(job.paramObj.parameters[i])
}
returnValues := reflectedFunc.Call(params)
Responses := []interface{}{}
for _, value := range returnValues {
Responses = append(Responses, value.Interface())
}
job.response = &ResponseObject{
job.id,
Responses,
}
job.responseChannel <- job.response
return job.response
}