forked from fiatjaf/jiq
-
Notifications
You must be signed in to change notification settings - Fork 0
/
jq.go
45 lines (39 loc) · 763 Bytes
/
jq.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
package jiq
import (
"bytes"
"context"
"fmt"
"os/exec"
"strings"
"time"
)
func jqrun(query string, json string, opts []string) (res string, err error) {
if query == "" {
query = "."
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
var b bytes.Buffer
opts = append(opts, query)
cmd := exec.Command("jq", opts...)
cmd.Stdin = bytes.NewBufferString(json)
cmd.Stdout = &b
cmd.Stderr = &b
err = cmd.Start()
if err != nil {
return
}
c := make(chan error, 1)
go func() { c <- cmd.Wait() }()
select {
case err = <-c:
cancel()
case <-ctx.Done():
cmd.Process.Kill()
<-c // Wait for it to return.
cancel()
err = fmt.Errorf("jq execution timeout")
return
}
res = strings.TrimSpace(b.String())
return
}