-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfunc.go
99 lines (91 loc) · 1.87 KB
/
func.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"time"
fdk "github.com/fnproject/fdk-go"
)
func main() {
fdk.Handle(fdk.HandlerFunc(myHandler))
}
type Person struct {
Name string `json:"name"`
Sleep float64 `json:"sleep"`
Dir string `json:"dir"`
Cat string `json:"file"`
Shell string `json:"shell"`
}
func myHandler(ctx context.Context, in io.Reader, out io.Writer) {
p := &Person{Name: "World"}
json.NewDecoder(in).Decode(p)
time.Sleep(time.Duration(p.Sleep * float64(time.Second)))
e := os.Environ()
msg := struct {
Msg string `json:"message"`
Env []string `json:"env"`
Files []string `json:"files"`
Err string `json:"error"`
Content []byte `json:"bytes"`
Stdout []byte `json:"stdout"`
Stderr []byte `json:"stderr"`
}{
Msg: fmt.Sprintf("Hello %s", p.Name),
Env: e,
}
if p.Dir != "" {
files := []string{}
if fs, err := ioutil.ReadDir(p.Dir); err == nil {
for _, f := range fs {
files = append(files, f.Name())
}
msg.Files = files
} else {
msg.Err = err.Error()
}
}
if p.Cat != "" {
if content, err := ioutil.ReadFile(p.Cat); err == nil {
msg.Content = content
} else {
msg.Err = err.Error()
}
}
if p.Shell != "" {
cmd := exec.Command("/bin/sh", "-c", p.Shell)
stdout, err1 := cmd.StdoutPipe()
stderr, err2 := cmd.StderrPipe()
outs := make(chan []byte, 1)
errs := make(chan []byte, 1)
if err1 != nil {
msg.Err = err1.Error()
goto done
}
if err2 != nil {
msg.Err = err2.Error()
goto done
}
go func() {
result, _ := ioutil.ReadAll(stdout)
stdout.Close()
outs <- result
}()
go func() {
result, _ := ioutil.ReadAll(stderr)
stderr.Close()
errs <- result
}()
if err := cmd.Run(); err != nil {
msg.Err = err.Error()
goto done
}
msg.Stdout = <- outs
msg.Stderr = <- errs
done:
}
json.NewEncoder(out).Encode(&msg)
}