forked from fieldryand/goflow
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperator.go
70 lines (62 loc) · 1.6 KB
/
operator.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 goflow
import (
"fmt"
"io"
"net/http"
"os/exec"
)
// An Operator implements a Run() method. When a job executes a task that
// uses the operator, the Run() method is called.
type Operator interface {
Run() (interface{}, error)
}
// Command executes a shell command.
type Command struct {
Cmd string
Args []string
}
// Run passes the command and arguments to exec.Command and captures the
// output.
func (o Command) Run() (interface{}, error) {
out, err := exec.Command(o.Cmd, o.Args...).Output()
return string(out), err
}
// Get makes a GET request.
type Get struct {
Client *http.Client
URL string
}
// Run sends the request and returns an error if the status code is
// outside the 2xx range.
func (o Get) Run() (interface{}, error) {
res, err := o.Client.Get(o.URL)
if err != nil {
return nil, err
} else if res.StatusCode < 200 || res.StatusCode > 299 {
return nil, fmt.Errorf("Received status code %v", res.StatusCode)
} else {
content, err := io.ReadAll(res.Body)
res.Body.Close()
return string(content), err
}
}
// Post makes a POST request.
type Post struct {
Client *http.Client
URL string
Body io.Reader
}
// Run sends the request and returns an error if the status code is
// outside the 2xx range.
func (o Post) Run() (interface{}, error) {
res, err := o.Client.Post(o.URL, "application/json", o.Body)
if err != nil {
return nil, err
} else if res.StatusCode < 200 || res.StatusCode > 299 {
return nil, fmt.Errorf("Received status code %v", res.StatusCode)
} else {
content, err := io.ReadAll(res.Body)
res.Body.Close()
return string(content), err
}
}