/
rest.go
70 lines (59 loc) · 1.49 KB
/
rest.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
package executor
import (
"encoding/base64"
"net/url"
"time"
"github.com/levigross/grequests"
)
type RestExec struct {
url string
timeout time.Duration
}
func NewRestExec(url string, timeout time.Duration) *RestExec {
return &RestExec{url: url, timeout: timeout}
}
type externalExecutionResponse struct {
Returncode uint32 `json:"returncode"`
Stdout string `json:"stdout"`
Stderr string `json:"stderr"`
Version string `json:"version"`
}
func (e *RestExec) Exec(code []byte, arg string, env interface{}) (ExecResult, error) {
executable := base64.StdEncoding.EncodeToString(code)
resp, err := grequests.Post(
e.url,
&grequests.RequestOptions{
Headers: map[string]string{
"Content-Type": "application/json",
},
JSON: map[string]interface{}{
"executable": executable,
"calldata": arg,
"timeout": e.timeout.Milliseconds(),
"env": env,
},
RequestTimeout: e.timeout,
},
)
if err != nil {
urlErr, ok := err.(*url.Error)
if !ok || !urlErr.Timeout() {
return ExecResult{}, err
}
// Return timeout code
return ExecResult{Output: []byte{}, Code: 111}, nil
}
if !resp.Ok {
return ExecResult{}, ErrRestNotOk
}
r := externalExecutionResponse{}
err = resp.JSON(&r)
if err != nil {
return ExecResult{}, err
}
if r.Returncode == 0 {
return ExecResult{Output: []byte(r.Stdout), Code: 0, Version: r.Version}, nil
} else {
return ExecResult{Output: []byte(r.Stderr), Code: r.Returncode, Version: r.Version}, nil
}
}