forked from gogap/go-wkhtmltox
-
Notifications
You must be signed in to change notification settings - Fork 0
/
command.go
86 lines (66 loc) · 1.17 KB
/
command.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
package wkhtmltox
import (
"bytes"
"errors"
"io"
"os/exec"
"syscall"
"time"
)
func execCommand(timeout time.Duration, data []byte, name string, args ...string) (result []byte, err error) {
cmd := exec.Command(name, args...)
cmd.SysProcAttr = &syscall.SysProcAttr{
Setpgid: true,
Pgid: 0,
}
stdin, err := cmd.StdinPipe()
if err != nil {
return
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return
}
stderr, err := cmd.StderrPipe()
if err != nil {
return
}
outBuf := bytes.NewBuffer(nil)
errBuf := bytes.NewBuffer(nil)
if err != nil {
return
}
err = cmd.Start()
if err != nil {
return
}
if len(data) > 0 {
_, err = io.Copy(stdin, bytes.NewBuffer(data))
if err != nil {
return
}
}
stdin.Close()
go io.Copy(outBuf, stdout)
go io.Copy(errBuf, stderr)
ch := make(chan error)
go func(cmd *exec.Cmd) {
defer close(ch)
ch <- cmd.Wait()
}(cmd)
select {
case err = <-ch:
case <-time.After(timeout):
cmd.Process.Kill()
err = errors.New("execute timeout")
return
}
if err != nil {
errStr := errBuf.String()
return nil, errors.New(errStr)
}
if outBuf.Len() > 0 {
return outBuf.Bytes(), nil
}
return
}